How to extract attachments from MSG and save them as a valid files with mail-parser in python?

708 views Asked by At

I'm using mail-parser to parse emails in MSG (.msg) file format and to extract its attachments.

import mailparser

mail = mailparser.parse_from_file_msg('example.msg')
attachments = mail.attachments
for att in attachments:
    file_name = att['filename']
    encoded_payload = att['payload']

Attachments are base64 encoded. I am not able to use win32com module in my environment. Is there a way to save the extracted encoded payloads as a valid files?

1

There are 1 answers

0
martink On

You can use base64.urlsafe_b64decode() which takes a bytes-like object or (as in this case) ASCII string to decode. The result is returned as a bytes object, therefore we can simple write it to a file which is opened with a wb access mode.

import mailparser
import base64

mail = mailparser.parse_from_file_msg('example.msg')
attachments = mail.attachments
for att in attachments:
    file_name = att['filename']
    encoded_payload = att['payload']
    with open(file_name, "wb") as att_file:
        att_file.write(base64.urlsafe_b64decode(encoded_payload))