簡體   English   中英

如何在Python和Outlook中使用for循環在電子郵件中保存所有附件?

[英]How to save all attachments in email using for loop in Python and Outlook?

如果我的電子郵件中有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循環,並且-在不產生任何錯誤的情況下-找到最后一個附件后停止運行?

看起來Attachments集合可以像普通列表一樣在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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM