# HG changeset patch # User Dennis Fink # Date 2022-07-19 11:54:17 # Node ID 9cb4b622c930323c92290abaf3f7e70cb27393ac # Parent c77b87b525ceaaf13b9542cee466ff89b34096ff Use context manager with stmp connection diff --git a/spaceapi/utils.py b/spaceapi/utils.py --- a/spaceapi/utils.py +++ b/spaceapi/utils.py @@ -76,22 +76,22 @@ def post_toot(toot): def post_email(subject, body): if "EMAIL_PASS" in current_app.config: - smtp_conn = smtplib.SMTP( - current_app.config["EMAIL_HOST"], port=current_app.config["EMAIL_PORT"] - ) - ssl_context = ssl.create_default_context() - smtp_conn.starttls(context=ssl_context) - smtp_conn.login( - current_app.config["EMAIL_USER"], current_app.config["EMAIL_PASS"] - ) + msg = email.message.EmailMessage(policy=email.policy.default) msg["To"] = current_app.config["EMAIL_ANNOUNCE_ADDRESS"] - msg["From"] = "spaceapibot <{email}>".format( - email=current_app.config["EMAIL_USER"] - ) + + email_user = current_app.config["EMAIL_USER"] + msg["From"] = "spaceapibot <{email}>".format(email=email_user) + msg["Subject"] = subject msg.set_content(body) - smtp_conn.send_message(msg) + + with smtplib.SMTP( + current_app.config["EMAIL_HOST"], port=current_app.config["EMAIL_PORT"] + ) as smtp: + smtp.starttls(context=ssl.create_default_context()) + smtp.login(email_user, current_app.config["EMAIL_PASS"]) + smtp.send_message(msg) class Singleton: