I check the attachments in the letter through the anti-virus system, if the attachment is malicious or suspicious, it must be removed from the letter and add the text that the attachment was deleted.

How can I effectively remove Content-Disposition: inline or Content-Disposition: attachment attachments? Is it necessary to collect a new letter (new email.Message object) and add attachments to it already? Can I probably somehow change the already existing email.Message object? And if it is impossible, how can you construct a new letter that can be of any complexity (you need to copy all the headers, all parts of the letter, for example, using msg.walk)?

    1 answer 1

    You can think of EmailMessage as a set of headers and content, which can be a list of other messages (a tree structure).

    Separate EmailMessage objects are mutable, so you can try replacing them locally. For example, to replace all pictures with text :

    for part in msg.walk(): if part.get_content_maintype() == 'image': part.clear_content() part.set_content("""\ Salut! The image is removed. --Pepé """) 

    Here is an example of how to replace a picture with a picture (with text) - it can be useful if a picture is inserted directly into the letter using cid (so that the text is visible in the client).

    To save a message to a file:

     with open('no-image.msg', 'wb') as file: file.write(bytes(msg)) 

    To send a message, for example, via gmail:

     import smtplib import ssl with smtplib.SMTP('smtp.gmail.com', timeout=10) as s: s.set_debuglevel(1) s.starttls(context=ssl.create_default_context()) s.login(gmail_user, gmail_password) s.send_message(msg) 
    • I get File "test.py", line 77, in handle msg_part.clear_content () AttributeError: 'Message' object has no attribute 'clear_content' —M Nikita
    • @MNikita code uses EmailMessage, not Message (use email.policy.default) - jfs