Skip to content
Snippets Groups Projects
Commit 50b65716 authored by Bjarke Madsen's avatar Bjarke Madsen
Browse files

use newer email API and send with UTF-8 support

parent 1c86e466
Branches
Tags
No related merge requests found
import smtplib
import threading
import logging
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from typing import Sequence, Union
from sqlalchemy import select
from flask import current_app
......@@ -22,11 +24,11 @@ Daniel and Jennifer (the Compendium admins)
""" # noqa: E501
def _send_mail(smtp_server, port, sender_email, recipients, message):
def _send_mail(smtp_server: str, port: int, recipients: Union[str, Sequence[str]], message: MIMEMultipart):
try:
with smtplib.SMTP(smtp_server, port) as server:
server.sendmail(from_addr=sender_email, to_addrs=recipients, msg=message)
server.sendmail(from_addr=message['From'], to_addrs=recipients, msg=message.as_string())
logger.debug('Successfully sent email')
except Exception:
logger.exception('Unable to send email:')
......@@ -53,16 +55,18 @@ def send_mail(
if not recipients:
recipients = admin_emails
subject = subject.replace('\n', ' ')
message = f"""Subject: {subject}\n\n{contents}"""
message = MIMEMultipart('alternative')
message['Subject'] = subject
message['From'] = current_app.config['MAIL_SENDER_EMAIL']
message['To'] = ', '.join(recipients)
message.attach(MIMEText(contents, 'plain', 'utf-8'))
smtp_server = current_app.config['MAIL_SERVER']
port = current_app.config['MAIL_PORT']
sender_email = current_app.config['MAIL_SENDER_EMAIL']
# spin off a thread since this can take some time..
logger.debug('Sending email')
thread = threading.Thread(target=_send_mail, args=(smtp_server, port, sender_email, recipients, message))
thread = threading.Thread(target=_send_mail, args=(smtp_server, port, recipients, message))
thread.start()
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment