python / cpython

The Python programming language
https://www.python.org
Other
63.79k stars 30.55k forks source link

EML as an attachment to an email not getting parsed #104005

Open gal-forer opened 1 year ago

gal-forer commented 1 year ago

Bug report

We send a byte string of an email that has an EML attachment, but when we parse the email we don't get the attachment in the object.

We ran the same code with a JPEG an a MSG attachments and it worked for them.

Our code is simple message = email.message_from_bytes(bt) where bt value is available here: https://drive.google.com/file/d/1_Y8UbDbTTrh4mn1SSGu7w2phWiLyPJJ7/view?usp=sharing

Your environment

DBJim commented 1 year ago

Hi!

This example works on windows with Python 3.10.10:

def parse_email(bt):
    msg = email.message_from_bytes(bt)
    output_directory = r"C:\Users\james\Downloads\attachments"
    email_path = os.path.join(output_directory, "email.eml")

    # save the email including the email attached to it
    with open(email_path, 'wb') as email_file:
        email_file.write(bt)
        print(f"Email saved to: {email_path}")

    # get the attachment and save it separately
    for part in msg.walk():
        if part.get_content_disposition() == 'attachment':
            attachment_name = part.get_filename()
            attachment_path = os.path.join(output_directory, attachment_name)
            with open(attachment_path, 'wb') as attachment_file:
                attachment_file.write(part.get_payload(decode=True))
            print(f"Attachment saved to: {attachment_path}")

Output:

Email saved to: C:\Users\james\Downloads\attachments\email.eml
Attachment saved to: C:\Users\james\Downloads\attachments\incident-229_phish_alert_sp2_2.0.0.0.msg

Process finished with exit code 0

-Do I understand correctly what you're trying to do?

-Does my example work for you? (maybe MacOS specific issue)

gal-forer commented 1 year ago

I tried the script but I got this error:

Traceback (most recent call last):
  File "/Users/gforer/dev/demisto/content/Packs/MailListener/Integrations/MailListenerV2/test.py", line 28, in <module>
    parse_email(bt)
  File "/Users/gforer/dev/demisto/content/Packs/MailListener/Integrations/MailListenerV2/test.py", line 22, in parse_email
    attachment_file.write(part.get_payload(decode=True))
TypeError: a bytes-like object is required, not 'NoneType'

the file I tried: https://drive.google.com/file/d/1ayuXqvI9QTrC1uwofko0h1VJ8kUWkv4A/view?usp=sharing

DBJim commented 1 year ago

What's the result when bt is the same byte string as you shared in your original post?

The second file you shared also failed for me, because there wasn't any handling for zero-byte attachments in my script.