如何在Python中使用win32com.client保存Outlook的附件? [英] How to save attachment from outlook using win32com.client in Python?
问题描述
我试图阅读电子邮件,并使用Python中的win32com模块将附件下载到我自己的文件夹,我停止获取附件对象:
Im trying to read email and download the attachment to my own folder using win32com module in Python, I stopped at getting the attachment 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')
最后4行中没有一个工作。 ..
None of the last 4 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')
没有错误,但工作目录中没有这样的文件。似乎该行被忽略了...
att.SaveAsFile('new.xlsx')
has no error, but there is no such file in the working directory. Seems that the line was just ignored...
有人可以帮忙吗?感谢提前!
Could anyone help? Thanks in advance!
推荐答案
只是为了更新,我已经通过在SaveAsFile中声明目录和文件名本身来解决这个问题:
Just to update, I have solved this issue by claiming both dir and the file name itself in SaveAsFile:
att.SaveAsFile(os.getcwd() + '\\new.xlsx')
这里并没有像我在这里看过的大多数线程,只需要放置路径。实际上需要路径和文件名。
It is not like most threads I've seen here saying that you only need to put path in it. Actually both path and file name are needed.
另外,怪异的是,你必须将os.getcwd()放在这里,因为Python不会识别当前正在运行的目录在我们使用getwd()设置工作目录后,我们可以写入此位置的任何文件。
Also, weirdly, you have to put os.getcwd() here since Python wouldn't recognize current running dir - in R, after we set working dir with getwd(), we are able to write to any file at this location.
干杯,
这篇关于如何在Python中使用win32com.client保存Outlook的附件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!