gpt4 book ai didi

python - 如何在 Python 中使用 win32com.client 从 outlook 保存附件?

转载 作者:太空狗 更新时间:2023-10-29 18:27:56 31 4
gpt4 key购买 nike

我尝试使用 Python 中的 win32com 模块阅读电子邮件并将附件下载到我自己的文件夹,我在获取附件对象时停止了:

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 行都不起作用...

>>> 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')没有报错,但是工作目录下没有这个文件。似乎该行被忽略了...

有人能帮忙吗?提前致谢!

最佳答案

更新一下,我通过在 SaveAsFile 中声明 dir 和文件名本身解决了这个问题:

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

它不像我在这里看到的大多数线程那样说您只需要在其中放入路径。实际上路径和文件名都需要。

此外,奇怪的是,您必须将 os.getcwd() 放在这里,因为 Python 无法识别当前运行的 dir - 在 R 中,在我们设置工作 dirgetwd(),我们可以在这个位置写入任何文件。

关于python - 如何在 Python 中使用 win32com.client 从 outlook 保存附件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22399835/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com