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
    session.Logon('','',0,1,0,0,'exchange.foo.com\nusername');
    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
        attachment.WriteToFile(filename)
    session.Logoff()


if __name__ == '__main__':
    main()

* Extra Special thanks to Sergey Golovchenko for helping out.

Post a Comment