From 5dacb3679033172af4aa079ee1e055f73becdf68 Mon Sep 17 00:00:00 2001 From: Robert Goldmann <deadlocker@gmx.de> Date: Fri, 1 May 2020 16:00:18 +0200 Subject: [PATCH] added MailHandler --- PythonLibs/MailHandler.py | 50 +++++++++++++++++++++++++++++++++++++++ PythonLibs/__init__.py | 1 + 2 files changed, 51 insertions(+) create mode 100644 PythonLibs/MailHandler.py diff --git a/PythonLibs/MailHandler.py b/PythonLibs/MailHandler.py new file mode 100644 index 0000000..1841015 --- /dev/null +++ b/PythonLibs/MailHandler.py @@ -0,0 +1,50 @@ +import smtplib +import ssl +from email.mime.multipart import MIMEMultipart +from email.mime.text import MIMEText +from typing import List, Dict + + +class MailHandler: + @staticmethod + def send_from_config(config: Dict, subject: str, content: str): + MailHandler.send(config['host'], + config['port'], + config['userName'], + config['password'], + config['receiverMails'], + subject, + content) + + @staticmethod + def send(host: str, port: int, userName: str, password: str, receiverMails: List[str], subject: str, content: str): + message = MIMEMultipart('alternative') + message['Subject'] = subject + message['From'] = userName + message['To'] = receiverMails + + # Create the plain-text and HTML version of your message + text = subject + html = '''\ + <html> + <body> + <h2>{subject}</h2> + {content} + </body> + </html> + '''.format(subject=subject, content=content) + + # Turn these into plain/html MIMEText objects + part1 = MIMEText(text, 'plain') + part2 = MIMEText(html, 'html') + + # Add HTML/plain-text parts to MIMEMultipart message + # The email client will try to render the last part first + message.attach(part1) + message.attach(part2) + + # Create secure connection with server and send email + context = ssl.create_default_context() + with smtplib.SMTP_SSL(host, port, context=context) as server: + server.login(userName, password) + server.sendmail(userName, receiverMails, message.as_string()) diff --git a/PythonLibs/__init__.py b/PythonLibs/__init__.py index 9f0fa13..2557fdf 100644 --- a/PythonLibs/__init__.py +++ b/PythonLibs/__init__.py @@ -1 +1,2 @@ from PythonLibs.DefaultLogger import DefaultLogger +from PythonLibs.MailHandler import MailHandler -- GitLab