From 9c9319c94ef295e2ffc81a8db667b517aec19bdd Mon Sep 17 00:00:00 2001 From: Son NK <> Date: Wed, 10 Jun 2020 13:57:23 +0200 Subject: [PATCH] handle emails sent to sender --- email_handler.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/email_handler.py b/email_handler.py index f7a61fc8..b4770bde 100644 --- a/email_handler.py +++ b/email_handler.py @@ -31,6 +31,7 @@ It should contain the following info: """ import email +import os import time import uuid from email import encoders @@ -63,6 +64,8 @@ from app.config import ( ALERT_SPAM_EMAIL, ALERT_SPF, POSTFIX_PORT, + SENDER, + SENDER_DIR, ) from app.email_utils import ( send_email, @@ -1019,6 +1022,27 @@ def handle_unsubscribe(envelope: Envelope): return "250 Unsubscribe request accepted" +def handle_sender_email(envelope: Envelope): + filename = ( + arrow.now().format("YYYY-MM-DD_HH-mm-ss") + "_" + random_string(10) + ".eml" + ) + filepath = os.path.join(SENDER_DIR, filename) + + with open(filepath, "wb") as f: + f.write(envelope.original_content) + + LOG.d("Write email to sender at %s", filepath) + + msg = email.message_from_bytes(envelope.original_content) + orig = get_orig_message_from_bounce(msg) + if orig: + LOG.warning( + "Original message %s -> %s saved at %s", orig["From"], orig["To"], filepath + ) + + return "250 email to sender accepted" + + def handle(envelope: Envelope, smtp: SMTP) -> str: """Return SMTP status""" # unsubscribe request @@ -1026,6 +1050,11 @@ def handle(envelope: Envelope, smtp: SMTP) -> str: LOG.d("Handle unsubscribe request from %s", envelope.mail_from) return handle_unsubscribe(envelope) + # emails sent to sender. Probably bounce emails + if SENDER and envelope.rcpt_tos == [SENDER]: + LOG.d("Handle email sent to sender from %s", envelope.mail_from) + return handle_sender_email(envelope) + # Whether it's necessary to apply greylisting if greylisting_needed(envelope.mail_from, envelope.rcpt_tos): LOG.warning(