LoginSignup
0
0

NDRメールマスク化

Posted at
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')
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0