简体   繁体   中英

How to filter outlook mails on a subject using Python and win32com.client?

I was trying to download attachments from outlook which satisfy a particular subject but i got an exception that have no idea how to correct my code from below is my code:

import win32com.client
import os
get_path = os.getcwd()
outlook = win32com.client.Dispatch("Outlook.Application").GetNameSpace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
message2 = messages.GetLast()
subject = message2.Subject
body = message2.body
sender = message2.Sender
attachments = message2.Attachments
for m in messages:
    if m.Subject == "Test Mail":
        for x in message2.Attachments:
            x.SaveASFile(os.path.join(get_path,x.FileName))
            print "successfully downloaded attachments"

and here is the problem:

Traceback (most recent call last):
  File "C:/Users/LENOVO USER/PycharmProjects/FlaskProject/EmailFilter/TestFile.py", line 4, in <module>
    outlook = win32com.client.Dispatch("Outlook.Application").GetNameSpace("MAPI")
  File "C:\Python27\lib\site-packages\win32com\client\__init__.py", line 95, in Dispatch
    dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx)
  File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 114, in _GetGoodDispatchAndUserName
    return (_GetGoodDispatch(IDispatch, clsctx), userName)
  File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 91, in _GetGoodDispatch
    IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch)
pywintypes.com_error: (-2147221005, 'Invalid class string', None, None)

As the traceback shows, the error is at the line where you define outlook . Actually, there is no cap S in GetNamespace so replace this line by:

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

but other errors occur, at the line where body is defined, a cap is mandatory for the attribute, such as body = message2.Body , and another cap issue in x.SaveASFile , it should be x.SaveAsFile

Finally, I'm not sure that your code will do what you describe as you try to download the attachments of message2 , being your last message, while you iterate through messages , I don't see the point then.

Let me know if you need more help or if I misunderstood your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM