expephalon-kumisms/core/classes/mail.py

48 lines
1.8 KiB
Python

import smtplib
import email
import email.utils
from urllib.parse import urlparse
from dbsettings.functions import getValue
class BaseMailProvider:
@property
def get_name(self):
return "Base Mail Provider"
@property
def get_logo(self):
return ""
def send_message(self, message):
raise NotImplementedError(f"{type(self)} does not implement send_message()!")
def send_mail(self, subject, content, recipients, cc=[], bcc=[], headers={}, sender=getValue("core.mail.sender", "expephalon@localhost")):
message = email.message_from_string(content)
headers["From"] = sender
headers["To"] = recipients if type(recipients) == str else ",".join(recipients)
headers["Cc"] = cc if type(cc) == str else ",".join(cc)
headers["Bcc"] = bcc if type(bcc) == str else ",".join(bcc)
headers["Subject"] = subject
headers["Message-ID"] = email.utils.make_msgid("expephalon", urlparse(getValue("core.base_url", "http://localhost/").split(":")[1]).netloc)
headers["Date"] = email.utils.formatdate()
for header, value in headers.items():
if value:
message.add_header(header, value)
message.set_charset("base64")
return self.send_message(message)
class SMTPMailProvider(BaseMailProvider):
def __init__(self, host=getValue("core.smtp.host", "localhost"), port=int(getValue("core.smtp.port", 0)), username=getValue("core.smtp.username", "") or None, password=getValue("core.smtp.password", "")):
self.smtp = smtplib.SMTP(host, port)
if username:
self.smtp.login(username, password)
@property
def get_name(self):
return "SMTP Mail"
def send_message(self, message):
return self.smtp.send_message(message, rcpt_options=['NOTIFY=SUCCESS,DELAY,FAILURE'])