使用Python从Outlook下载附件

时间:2018-10-25 04:49:48

标签: python python-3.x outlook win32com

我正在尝试使用Python从Outlook下载附件,到目前为止,我已经能够按主题行下载附件,但就我而言,我想从多封电子邮件中下载多个附件,其中主题行以某个字符串开头,例如: 主题是:像这样的查询123654,查询56975,查询5698,我想下载所有以“ Query”开头的主题名称。 我当前的代码如下:

from win32com.client import Dispatch
outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder("6")
all_inbox = inbox.Items
val_date = datetime.date.today()

sub_today = 'Query 123654'
att_today = ''
for msg in all_inbox:
    if msg.Subject == sub_today and msg.Senton.date() == val_date:
        break

for att in msg.Attachments:
    if att.FileName == att_today:
        break

try:
    att.SaveAsFile('C:\\Offline Feeds\\Attachments' + '\\'+ att.FileName)
    messagebox.showinfo("SUCCESSFUL","Attachments Downloaded")
except:
    messagebox.showerror("ERROR","Attachment Download Failed")

1 个答案:

答案 0 :(得分:0)

您可以使用find()搜索特定数据。

sub_today = 'Query'

if msg.Subject.find(sub_today) != -1 break

如果主题不包含“查询”,则将返回“ -1”。

这是完整的代码:

from win32com.client import Dispatch
outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder("6")
all_inbox = inbox.Items
val_date = datetime.date.today()

sub_today = 'Query'
att_today = ''
for msg in all_inbox:
    if msg.Subject.find(sub_today) != -1 and msg.Senton.date() == val_date:
        break

for att in msg.Attachments:
    if att.FileName == att_today:
        break

try:
    att.SaveAsFile('C:\\Offline Feeds\\Attachments' + '\\'+ att.FileName)
    messagebox.showinfo("SUCCESSFUL","Attachments Downloaded")
except:
    messagebox.showerror("ERROR","Attachment Download Failed")

有关更多信息,请参考此链接:

Python String find() Method