From 0e3c46d944d2ff8194b7c9897b52ceb76fcd397e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Casaj=C3=BAs?= Date: Wed, 6 Apr 2022 17:31:46 +0200 Subject: [PATCH] Save original envelope for debugging --- app/email_utils.py | 23 ++++++++++++++++++++++- email_handler.py | 5 +++-- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/app/email_utils.py b/app/email_utils.py index f84b755f..a0ce7a0a 100644 --- a/app/email_utils.py +++ b/app/email_utils.py @@ -6,6 +6,9 @@ import random import time import uuid from copy import deepcopy + +from aiosmtpd.smtp import Envelope + from email import policy, message_from_bytes, message_from_string from email.header import decode_header, Header from email.message import Message, EmailMessage @@ -1432,7 +1435,7 @@ def save_email_for_debugging(msg: Message, file_name_prefix=None) -> str: if TEMP_DIR: file_name = str(uuid.uuid4()) + ".eml" if file_name_prefix: - file_name = file_name_prefix + file_name + file_name = "{}-{}".format(file_name_prefix, file_name) with open(os.path.join(TEMP_DIR, file_name), "wb") as f: f.write(msg.as_bytes()) @@ -1443,6 +1446,24 @@ def save_email_for_debugging(msg: Message, file_name_prefix=None) -> str: return "" +def save_envelope_for_debugging(envelope: Envelope, file_name_prefix=None) -> str: + """Save envelope for debugging to temporary location + Return the file path + """ + if TEMP_DIR: + file_name = str(uuid.uuid4()) + ".eml" + if file_name_prefix: + file_name = "{}-{}".format(file_name_prefix, file_name) + + with open(os.path.join(TEMP_DIR, file_name), "wb") as f: + f.write(envelope.original_content) + + LOG.d("envelope saved to %s", file_name) + return file_name + + return "" + + def get_spamd_result(msg: Message) -> Optional[SpamdResult]: spam_result_header = msg.get_all(headers.SPAMD_RESULT) if not spam_result_header: diff --git a/email_handler.py b/email_handler.py index 3286b9d8..a2d56620 100644 --- a/email_handler.py +++ b/email_handler.py @@ -131,6 +131,7 @@ from app.email_utils import ( get_mailbox_bounce_info, save_email_for_debugging, get_spamd_result, + save_envelope_for_debugging, ) from app.errors import ( NonReverseAliasInReplyPhase, @@ -2584,8 +2585,8 @@ class MailHandler: envelope.rcpt_tos, msg[headers.FROM], msg[headers.TO], - save_email_for_debugging( - msg, file_name_prefix=e.__class__.__name__ + save_envelope_for_debugging( + envelope, file_name_prefix=e.__class__.__name__ ), # todo: remove ) return status.E404