Thursday, 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.

2 comments:

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:

http://timgolden.me.uk/python/win32_how_do_i/replace-outlook-attachments-with-links.html

Corey Goldberg said...

thanks Tim.

I actually ended up finding the answer with some help at StackOverflow: http://stackoverflow.com/questions/448034/multithreaded-resource-access-where-do-i-put-my-locks