January 15, 2009

Python - Read Outlook Email and Save Embedded Attachments

I was struggling with this for days, so I figured I should post the code so others can see how to do it.

The following script will read the last email in an Outlook mailbox and save the attachments. It uses the CDO COM Interface to interact with Outlook/Exchange.

#!/usr/bin/env python
# Read the last email in an Outlook mailbox and save the attachments.

from win32com.client import Dispatch

def main():   
    session = Dispatch('MAPI.session')
    #session.Logon('Outlook')  # for local mailbox
    inbox = session.Inbox
    message = inbox.Messages.GetLast()
    attachments = message.Attachments
    for i in range(attachments.Count):
        attachment = attachments.Item(i + 1) # indexes are 1 based
        filename = 'c:\\tempfile_%i' % i

if __name__ == '__main__':

* Extra Special thanks to Sergey Golovchenko for helping out.


Tim Golden said...

Sorry you had to struggle :) Did you post to the python/python-win32 lists? I think that question's been answered a couple of times before. Here's my take:


Gyula Gergő said...

Very good solution, thank you.

Anonymous said...

Hi Corey,
Thanks for the solution. Normally it would have helped me, but unfortunately my attachments were of type 4 :-(

Just FYI: I'd like to refer to this discussion:

My aim was to extract some information from my attachments. Of course that is still possible as is pointed out in the above-mentioneed discussion, but I'm leaving it lying down for the mean time. Regards, Dobedani

Vamsi said...

How do we get the name of the attachment in the Email.Checked the Oject model but could not find it.