Files
WGDashboard/src/modules/Email.py

70 lines
3.0 KiB
Python
Raw Normal View History

2025-01-08 18:09:05 +08:00
import os.path
import smtplib
from email import encoders
from email.header import Header
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formataddr
class EmailSender:
def __init__(self, DashboardConfig):
self.smtp = None
self.DashboardConfig = DashboardConfig
2025-01-19 14:04:21 +08:00
if not os.path.exists('../attachments'):
os.mkdir('../attachments')
2025-01-08 18:09:05 +08:00
def Server(self):
return self.DashboardConfig.GetConfig("Email", "server")[1]
def Port(self):
return self.DashboardConfig.GetConfig("Email", "port")[1]
def Encryption(self):
return self.DashboardConfig.GetConfig("Email", "encryption")[1]
def Username(self):
return self.DashboardConfig.GetConfig("Email", "username")[1]
def Password(self):
return self.DashboardConfig.GetConfig("Email", "email_password")[1]
def SendFrom(self):
return self.DashboardConfig.GetConfig("Email", "send_from")[1]
def ready(self):
2025-01-13 16:47:15 +08:00
print(self.Server())
2025-01-08 18:09:05 +08:00
return len(self.Server()) > 0 and len(self.Port()) > 0 and len(self.Encryption()) > 0 and len(self.Username()) > 0 and len(self.Password()) > 0
def send(self, receiver, subject, body, includeAttachment = False, attachmentName = ""):
if self.ready():
try:
self.smtp = smtplib.SMTP(self.Server(), port=int(self.Port()))
self.smtp.ehlo()
if self.Encryption() == "STARTTLS":
self.smtp.starttls()
self.smtp.login(self.Username(), self.Password())
message = MIMEMultipart()
message['Subject'] = subject
message['From'] = formataddr((Header(self.SendFrom()).encode(), self.Username()))
message["To"] = receiver
2025-01-13 16:47:15 +08:00
message.attach(MIMEText(body, "plain"))
2025-01-08 18:09:05 +08:00
if includeAttachment and len(attachmentName) > 0:
2025-01-19 14:04:21 +08:00
attachmentPath = os.path.join('../attachments', attachmentName)
2025-01-08 18:09:05 +08:00
if os.path.exists(attachmentPath):
attachment = MIMEBase("application", "octet-stream")
2025-01-19 14:04:21 +08:00
with open(os.path.join('../attachments', attachmentName), 'rb') as f:
2025-01-08 18:09:05 +08:00
attachment.set_payload(f.read())
encoders.encode_base64(attachment)
attachment.add_header("Content-Disposition", f"attachment; filename= {attachmentName}",)
message.attach(attachment)
else:
self.smtp.close()
return False, "Attachment does not exist"
self.smtp.sendmail(self.Username(), receiver, message.as_string())
self.smtp.close()
return True, None
except Exception as e:
2025-01-13 16:47:15 +08:00
return False, f"Send failed | Reason: {e}"
return False, "SMTP not configured"