diff --git a/copanier/emails.py b/copanier/emails.py index a4ac7ff..88ca8d1 100644 --- a/copanier/emails.py +++ b/copanier/emails.py @@ -1,10 +1,4 @@ -import smtplib -from email.message import EmailMessage -from email.mime.multipart import MIMEMultipart -from email.mime.text import MIMEText -from email.mime.base import MIMEBase -from email.mime.base import MIMEBase -from email import encoders +from emails import Message from . import config @@ -13,37 +7,31 @@ def send(to, subject, body, html=None, copy=None, attachments=None): if not attachments: attachments = [] - msg = MIMEMultipart("alternative") - msg["Subject"] = subject - msg["From"] = config.FROM_EMAIL - msg["To"] = to - msg["Bcc"] = copy if copy else config.FROM_EMAIL + message = Message( + text=body, html=html, subject=subject, mail_from=config.FROM_EMAIL + ) - for file_name, attachment in attachments: - part = MIMEBase( - "application", - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=utf-8", + for filename, attachment in attachments: + message.attach( + filename=filename, + data=attachment, + mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=utf-8", ) - part.set_payload(attachment) - part.add_header("Content-Disposition", "attachment", filename=file_name) - encoders.encode_base64(part) - msg.attach(part) - - msg.attach(MIMEText(body, "plain")) - if html: - msg.attach(MIMEText(html, "html")) if not config.SEND_EMAILS: body = body.replace("https", "http") return print("Sending email", str(body)) - try: - server = smtplib.SMTP_SSL(config.SMTP_HOST) - server.login(config.SMTP_LOGIN, config.SMTP_PASSWORD) - server.send_message(msg) - except smtplib.SMTPException: - raise RuntimeError - finally: - server.quit() + + message.send( + to=to, + smtp={ + "host": config.SMTP_HOST, + "user": config.SMTP_LOGIN, + "password": config.SMTP_PASSWORD, + "port": "465", + "ssl": True, + }, + ) def send_from_template(env, template, to, subject, **params): diff --git a/requirements-dev.txt b/requirements-dev.txt index cce53fe..dabb732 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -4,3 +4,4 @@ pytest-asyncio usine pyquery pytest-watch +python-emails \ No newline at end of file diff --git a/setup.cfg b/setup.cfg index b2306ff..d802a36 100644 --- a/setup.cfg +++ b/setup.cfg @@ -15,6 +15,7 @@ install_requires = minicli==0.4.4 python-slugify==3.0.2 debts==0.4 + emails==0.5 [options.extras_require] dev =