Python Exchangelib read attached email

477 views Asked by At

I'm having some trouble to figure out how to read an attached email inside a email. I can save it as an attachment, but what I really trying to achiev is read the content of that email.

Some background: I got a customer who sends me data using email (bad practice indeed, but right now is the only way available). Some times he sends me a simple one with a spreadsheet. I can open it, save the attachment, read the spreadsheet normally, no big deal.

But some times he send me 3 or 4 simple emails attached into a single one, each attachment is a .msg (simple email with a spreadsheet) and I'm struggling to read it and save the spreadsheet attachment.

1

There are 1 answers

0
Hugo Vares On

Found it!

    for attach in item.attachments:    
        if not isinstance(attach, ItemAttachment):
            continue
        if not isinstance(attach.item, Message):
            continue
        for sub_attachment in attach.item.attachments:    
            if not isinstance(sub_attachment, FileAttachment):
                continue
            file_path = os.path.join(r'your_local_path_here', sub_attachment.name)
            with open(file_path, 'wb') as f:
                f.write(sub_attachment.content)