import email
from email import policy
from email.parser import BytesParser
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# NDRメールのファイルパス
ndr_email_path = 'path/to/ndr_email.eml'
def mask_message_body(ndr_email_path):
# メッセージをパース
with open(ndr_email_path, 'rb') as f:
msg = BytesParser(policy=policy.default).parse(f)
if msg.get_content_type() != 'multipart/report':
raise ValueError('This is not a multipart/report email')
# 新しいmultipart/reportメッセージを作成
multipart_report = MIMEMultipart('report', report_type='delivery-status')
multipart_report.set_boundary(msg.get_boundary())
for part in msg.iter_parts():
content_type = part.get_content_type()
if content_type == 'text/plain':
multipart_report.attach(part)
elif content_type == 'message/delivery-status':
multipart_report.attach(part)
elif content_type == 'message/rfc822':
original_message = part.get_payload(0)
# メッセージヘッダを保持
headers = original_message.as_string().split('\n\n', 1)[0]
# 本文をマスク化
original_body = original_message.get_payload()
masked_body = 'x' * len(original_body)
# 新しいmessage/rfc822パートを作成
masked_message = headers + '\n\n' + masked_body
masked_part = MIMEText(masked_message, 'rfc822')
masked_part.replace_header('Content-Type', 'message/rfc822')
multipart_report.attach(masked_part)
else:
multipart_report.attach(part)
return multipart_report
masked_email = mask_message_body(ndr_email_path)
# マスク化されたメールをファイルに保存
with open('masked_ndr_email.eml', 'w') as f:
f.write(masked_email.as_string())
print('Masked NDR email saved to masked_ndr_email.eml')
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme
List of users who liked
00