How to save attachment from Outlook using win32com.client in Python?

I am trying to read the email and upload the attachment to my own folder using the win32com module in Python, I settled on getting the binding object:

from win32com.client import Dispatch import datetime as date outlook = Dispatch("Outlook.Application").GetNamespace("MAPI") inbox = outlook.GetDefaultFolder("6") all_inbox = inbox.Items val_date = date.date.today() sub_today = 'Hi' att_today = 'Attachment.xlsx' for msg in all_inbox: if msg.Subject == sub_today: break for att in msg.Attachments: if att.FileName == att_today: break att.SaveAsFile('new.xlsx') att.ExtractFile('new.xlsx') open(att) att.WriteToFile('x') 

None of the last four lines work ...

 >>> att.ExtractFile('new.xlsx') raise AttributeError("%s.%s" % (self._username_, attr)) AttributeError: <unknown>.ExtractFile >>> open(att) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: coercing to Unicode: need string or buffer, instance found >>> att.WriteToFile('x') raise AttributeError("%s.%s" % (self._username_, attr)) AttributeError: <unknown>.WriteToFile 

att.SaveAsFile('new.xlsx') does not have an error, but there is no such file in the working directory. It seems the line was just ignored ...

Can anyone help? Thanks in advance!

+10
python email outlook win32com
source share
4 answers

Just for the update, I solved this problem by requiring both dir and file name in SaveAsFile:

 att.SaveAsFile(os.getcwd() + '\\new.xlsx') 

This is not like most threads I saw here, saying that you only need to specify a path. In fact, both the path and the file name are required.

Also, weird, you have to put os.getcwd () here, since Python will not recognize the current dir - in R executable, after we set the working directory with getwd (), we can write to any file on This location, etc.

Greetings

+10
source share

Where do you think the current working directory is? I would say that you are looking at the wrong folder, SaveAsFile generally works just fine.

Just pass the full path to SaveAsFile , which should solve your problem.

+2
source share

In Windows 10, starting this program without folder information saved the file in the directory of my user documents (for example, C: \ Users {userid} \ Documents)

0
source share

I'm definitely looking for this code - thank you very much (especially for posting the solution). When I read the code, I was interested to know what "val_date = date.date.today ()" should do?

0
source share

All Articles