Search code examples
pythonemailoutlookattachmentwin32com

Using Python to access outlook with win32com


I'm struggling with python integration with outlook using win32com.client.

All I am trying to do is get the most recent email from outlook and (at the moment) retrieve and print the name of the attachment

The code I'm trying to use:

import win32com.client

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespcae("MAPI")

inbox = outlook.GetDefaultFolder(6)

message = inbox.GetLast()

att = message.Attachmets 

print (att.filename)

Output

com_error: (-2147221005, 'Invalid class string', None, None)

Any help would really be appreciated.


Solution

  • The error is Outlook can't be found on the system but You have also misspelled GetNamespace, you have GetNamespcae

    Change inbox.GetLast(), to messages = inbox.Items then message = messages.GetLast()

    Example

    import win32com.client
    
    outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
    
    inbox = outlook.GetDefaultFolder(6)
    messages = inbox.Items
    messages.Sort('[ReceivedTime]', False)
    message = messages.GetLast()
    
    for attachment in message.Attachments:
        print(attachment.FileName)
    

    Here is another example with filter https://stackoverflow.com/a/57931132/4539709