Use external python-emails library.

This commit is contained in:
Alexis M 2019-10-04 22:22:24 +02:00
parent 1039198a6d
commit 8fbb02d06a
3 changed files with 22 additions and 32 deletions

View file

@ -1,10 +1,4 @@
import smtplib from emails import Message
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 . import config from . import config
@ -13,37 +7,31 @@ def send(to, subject, body, html=None, copy=None, attachments=None):
if not attachments: if not attachments:
attachments = [] attachments = []
msg = MIMEMultipart("alternative") message = Message(
msg["Subject"] = subject text=body, html=html, subject=subject, mail_from=config.FROM_EMAIL
msg["From"] = config.FROM_EMAIL
msg["To"] = to
msg["Bcc"] = copy if copy else config.FROM_EMAIL
for file_name, attachment in attachments:
part = MIMEBase(
"application",
"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")) for filename, attachment in attachments:
if html: message.attach(
msg.attach(MIMEText(html, "html")) filename=filename,
data=attachment,
mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=utf-8",
)
if not config.SEND_EMAILS: if not config.SEND_EMAILS:
body = body.replace("https", "http") body = body.replace("https", "http")
return print("Sending email", str(body)) return print("Sending email", str(body))
try:
server = smtplib.SMTP_SSL(config.SMTP_HOST) message.send(
server.login(config.SMTP_LOGIN, config.SMTP_PASSWORD) to=to,
server.send_message(msg) smtp={
except smtplib.SMTPException: "host": config.SMTP_HOST,
raise RuntimeError "user": config.SMTP_LOGIN,
finally: "password": config.SMTP_PASSWORD,
server.quit() "port": "465",
"ssl": True,
},
)
def send_from_template(env, template, to, subject, **params): def send_from_template(env, template, to, subject, **params):

View file

@ -4,3 +4,4 @@ pytest-asyncio
usine usine
pyquery pyquery
pytest-watch pytest-watch
python-emails

View file

@ -15,6 +15,7 @@ install_requires =
minicli==0.4.4 minicli==0.4.4
python-slugify==3.0.2 python-slugify==3.0.2
debts==0.4 debts==0.4
emails==0.5
[options.extras_require] [options.extras_require]
dev = dev =