如何在Python和Outlook中使用for循环保存电子邮件中的所有附件?

时间:2017-07-28 16:55:33

标签: python email outlook pywin32

如果我在电子邮件中有1个附件,这是我的代码,它运行得非常好。当电子邮件中有多个附件时,问题就出现了,我想要执行所有附件功能。

def get_email():
    import win32com.client
    import os
    import time
    import datetime as dt

    date_time = time.strftime('%m-%d-%Y')

    outlook = win32com.client.Dispatch("Outlook.Application").GetNameSpace("MAPI")

    inbox = outlook.GetDefaultFolder(6)

    messages = inbox.Items
    message = messages.GetFirst()  # any time calling GetFirst(), you can get GetNext()....
    # body_content = message.body

    try:
        attachments = message.Attachments
        attachment = attachments.Item(1)
        report_name = date_time + '_' + attachment.FileName

        attachment.SaveASFile(os.getcwd() + '\\' + report_name)
        print('Attachment saved: ' + report_name)

    except: #***********add error logging here**************
        print('No attachment found.')

我如何将其置于for循环中并说 - 对于每个x,attachment = attachments.Item(x) - 保存该附件,并根据刚刚保存的附件运行另一个函数。有没有办法我可以定义x变量来给我电子邮件中的附件数量,然后通过for循环运行它?或者有没有办法运行for循环并且 - 没有产生任何错误 - 一旦找到最后一个附件就停止?

1 个答案:

答案 0 :(得分:1)

看起来Attachments collection可以在for循环中工作,就像普通列表一样。我得到以下内容以保存电子邮件中的每个附件,而不是在没有附件的电子邮件中抛出错误:

import win32com.client
import os
import time
import datetime as dt

date_time = time.strftime('%m-%d-%Y')

outlook = win32com.client.Dispatch("Outlook.Application").GetNameSpace("MAPI")

inbox = outlook.GetDefaultFolder(6)

messages = inbox.Items
message = messages.GetFirst()

attachments = message.Attachments

# The following line works, so you can see how many attachments are on an item
print len(attachments)
# Here's another way to get the number of attachments
print attachments.Count

# since attachments works similar to a list, a for loop works
# if there are no attachments, it won't enter the for loop, and won't throw an error
for attachment in attachments:
    report_name = date_time + '_' + attachment.FileName

    attachment.SaveASFile(os.getcwd() + '\\' + report_name)
    print('Attachment saved: ' + report_name)