55 lines
1.8 KiB
Python
55 lines
1.8 KiB
Python
import smtplib
|
|
from email.mime.text import MIMEText
|
|
from email.mime.multipart import MIMEMultipart
|
|
|
|
from flaschengeist import logger
|
|
from flaschengeist.models.user import User
|
|
from flaschengeist.utils.hook import HookAfter
|
|
from flaschengeist.controller import userController
|
|
from flaschengeist.controller.messageController import Message
|
|
|
|
from . import Plugin
|
|
|
|
|
|
class MailMessagePlugin(Plugin):
|
|
def __init__(self, entry_point, config):
|
|
super().__init__(entry_point, config)
|
|
self.server = config["SERVER"]
|
|
self.port = config["PORT"]
|
|
self.user = config["USER"]
|
|
self.password = config["PASSWORD"]
|
|
self.crypt = config["CRYPT"]
|
|
self.mail = config["MAIL"]
|
|
|
|
@HookAfter("send_message")
|
|
def dummy_send(msg):
|
|
self.send_mail(msg)
|
|
|
|
def send_mail(self, msg: Message):
|
|
if isinstance(msg.receiver, User):
|
|
if not msg.receiver.mail:
|
|
logger.warning("Could not send Mail, mail missing: {}".format(msg.receiver))
|
|
return
|
|
recipients = [msg.receiver.mail]
|
|
else:
|
|
recipients = userController.get_user_by_role(msg.receiver)
|
|
|
|
mail = MIMEMultipart()
|
|
mail["From"] = self.mail
|
|
mail["To"] = ", ".join(recipients)
|
|
mail["Subject"] = msg.subject
|
|
mail.attach(MIMEText(msg.message))
|
|
if not hasattr(self, "smtp"):
|
|
self.__connect()
|
|
self.smtp.sendmail(self.mail, recipients, mail.as_string())
|
|
|
|
def __connect(self):
|
|
if self.crypt == "SSL":
|
|
self.smtp = smtplib.SMTP_SSL(self.server, self.port)
|
|
elif self.crypt == "STARTTLS":
|
|
self.smtp = smtplib.SMTP(self.server, self.port)
|
|
self.smtp.starttls()
|
|
else:
|
|
raise ValueError("Invalid CRYPT given")
|
|
self.smtp.login(self.user, self.password)
|