windows下如何用python抓取邮件内容和附件_如何在Python中使用win32com.client保存Outlook的附件?...

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')

None of the last 4 lines work...

>>> att.ExtractFile('new.xlsx')

raise AttributeError("%s.%s" % (self._username_, attr))

AttributeError: .ExtractFile

>>> open(att)

Traceback (most recent call last):

File "", line 1, in

TypeError: coercing to Unicode: need string or buffer, instance found

>>> att.WriteToFile('x')

raise AttributeError("%s.%s" % (self._username_, attr))

AttributeError: .WriteToFile

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!

解决方案

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.

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.

Cheers,

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值