如何使用python从outlook下载所有附件?

时间:2018-05-22 18:00:39

标签: python-3.x email outlook

问题:

在一封邮件中,我将有多个附件,我需要全部下载。

我该怎么做?

我的代码:

import win32com.client
import os
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6) # "6" refers to the index of a folder - in this case the inbox. You can change that number to reference
messages = inbox.Items
message = messages.GetFirst()
subject = message.Subject
#
get_path = 'C:\\Users\\test\\Desktop\\resumes'

for m in messages:
    if m.Subject == "FW: Opportunity with Mindtree | Automotive Infotainment |":

        print (message)
        attachments = message.Attachments
        attachment = attachments.Item(1)
        attachment.SaveASFile(os.path.join(get_path,attachment.FileName)) #Saves to the attachment to current folder
        print (attachment)
        message = messages.GetNext()

    else:
        message = messages.GetNext()

2 个答案:

答案 0 :(得分:1)

您的代码还有其他问题,但这应该可以使您获得多个附件:

import win32com.client
import os
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6) # "6" refers to the index of a folder - in this case the inbox. You can change that number to reference
messages = inbox.Items
message = messages.GetFirst()
subject = message.Subject
#
get_path = 'C:\\Users\\test\\Desktop\\resumes'

for m in messages:
    if m.Subject == "FW: Opportunity with Mindtree | Automotive Infotainment |":

        print (message)
        attachments = message.Attachments
        num_attach = len([x for x in attachments]))
            for x in range(1, num_attach):
            attachment = attachments.Item(x)
            attachment.SaveASFile(os.path.join(get_path,attachment.FileName))
        print (attachment)
        message = messages.GetNext()

    else:
        message = messages.GetNext()

答案 1 :(得分:0)

import win32com.client
import os
import datetime as dt

mydesktop = os.path.expanduser('~') + '/Desktop/'
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")

print (dt.datetime.now())

# setup range for outlook to search emails (so we don't go through the entire inbox)
lastWeekDateTime = dt.datetime.now() - dt.timedelta(days = 4)
lastWeekDateTime = lastWeekDateTime.strftime('%m/%d/%Y %H:%M %p')

# Select main Inbox
inbox = outlook.GetDefaultFolder(6)

# Optional:  Select main Inbox, look in subfolder "Test"
#inbox = outlook.GetDefaultFolder(6).Folders["Test"]

messages = inbox.Items

# Only search emails in the time range above:
messages = messages.Restrict("[ReceivedTime] >= '" + lastWeekDateTime +"'")

print ('Reading Inbox, including Inbox Subfolders...')

# Download a select attachment ---------------------------------------
# Create a folder to capture attachments.
Myfolder = mydesktop + 'Outlook Export/'
if not os.path.exists(Myfolder): os.makedirs(Myfolder)

try:
    for message in list(messages):
        try:
            s = message.sender
            s = str(s)
            print('Sender:' , message.sender)
            for att in message.Attachments:
                # Give each attachment a path and filename
                outfile_name1 = Myfolder + att.FileName
                # save file 
                att.SaveASFile(outfile_name1)
                print('Saved file:', outfile_name1)

        except Exception as e:
            print("type error: " + str(e))
            x=1

except Exception as e:
    print("type error: " + str(e))
    x=1

#Delete unused file types (like .png)-----------------------------------------

test = os.listdir(Myfolder)

for item in test:
    if item.endswith(".png"):
        os.remove(os.path.join(Myfolder, item))