# # Aura Engine (https://gitlab.servus.at/aura/engine) # # Copyright (C) 2017-2020 - The Aura Engine Team. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import smtplib from email.message import EmailMessage class MailingException(Exception): """ Thrown when some mail cannot be sent. """ class AuraMailer(): """ Service to send emails to Aura administrators. """ config = None def __init__(self, config): """ Constructor to initialize service with Aura `config`. Args: config (AuraConfig): The configuration with the mail server details """ self.config = config self.admin_mails = config.get("admin_mail") # # PUBLIC METHODS # def send_admin_mail(self, subject, body): """ Sends an email to the administrator as defined in the configuration. Args: subject (String): The email's subject body (String): The email's body text """ admin_mails = self.admin_mails.split() for mail_to in admin_mails: self.__send(mail_to, subject, body) # # PRIVATE METHODS # def __send(self, mail_to, subject, body): """ Sends an email to the given address. Args: subject (String): The email's subject body (String): The email's body text """ # read config mail_server = self.config.get("mail_server") mail_port = self.config.get("mail_server_port") mail_user = self.config.get("mail_user") mail_pass = self.config.get("mail_pass") from_mail = self.config.get("from_mail") # check settings if mail_server == "": raise MailingException("Mail Server not set") if mail_port == "": raise MailingException("Mailserver Port not set") if mail_user == "": raise MailingException("Mail user not set") if mail_pass == "": raise MailingException("No Password for mailing set") if from_mail == "": raise MailingException("From Mail not set") # stuff the message together and ... msg = EmailMessage() msg.set_content(body) mailsubject_prefix = self.config.get("mailsubject_prefix") if mailsubject_prefix == "": msg["Subject"] = subject else: msg["Subject"] = mailsubject_prefix + " " + subject msg["From"] = from_mail msg["To"] = mail_to # ... send the mail try: server = smtplib.SMTP(mail_server, int(mail_port)) server.starttls() server.login(mail_user, mail_pass) server.send_message(msg) server.quit() except Exception as e: raise MailingException(str(e))