简体   繁体   中英

Download Attachments From Outlook using Pythin Script

Now I wrote a code in which to run it every day to get the attachments of yesterday's emails. when I run it the attachment isn't downloaded and instead I get a file named "@".

below is the code:

import win32com.client
import os
from datetime import datetime, date, time, timedelta

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6).Folders.Item("Inbox Subfolder Name") 
messages = inbox.Items
message = messages.GetFirst()
subject = message.Subject

# Get yesterdays date for the purpose of getting emails from this date
d = (date.today() - timedelta (days=1)).strftime("%y-%m-%d")
yesterdaydate=("20"+d)
print yesterdaydate

get_path_clt1 = "Folder Location" + yesterdaydate+"\\"

if os.path.exists(get_path_clt1):
    print " File Exists"
else:
    os.mkdir(get_path_clt1)


for m in messages:
    date = str(m.senton)
    date_time_obj = datetime.strptime(date,'%m/%d/%y %H:%M:%S')
    messagedate=date_time_obj.date()

    if str(yesterdaydate) == str(messagedate) and (m.Subject == "Subject Name to compare") :
        print (message)
        print (messagedate)
        attachments = message.Attachments
        num_attach = len([x for x in attachments])
        print("test-1")
        for x in range(1, num_attach+1):
            print("test-in-1")
            attachment = attachments.Item(x)
            attachment.SaveAsFile(os.path.join(get_path_clt1,attachment.FileName))
            print (attachment)
            print ("---------------------")
            break
        message = messages.GetNext()

    else:
        message = messages.GetNext()

First of all, there is no need to iterate over all attachment to get the number:

 num_attach = len([x for x in attachments])

Instead, you can use the Attachments.Count property which returns an integer indicating the count of objects in the specified collection.

Second, make sure that you specify a valid filename:

 attachment.SaveAsFile(os.path.join(get_path_clt1,attachment.FileName))

I'd suggest checking the attachment.FileName value before or generating your own.

Finally, you may check the Attachment.Type property which returns an OlAttachmentType constant indicating the type of the specified object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM