简体   繁体   中英

Download attachment from Outlook using Python

I am trying to download attachments from Outlook using Python, as of now am able to download the attachments by subject line but in my case I want to download multiple attachments from multiple emails where subject line starts with some string, For Ex: Subjects are: Query 123654, Query 56975, Query 5698 like this and I want to download all of them where subject name starts with "Query". My current code is below:

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")

You could use find() to search specific data.

sub_today = 'Query'

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

If subject not include “Query”, it will return “-1”.

This is the complete code:

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")

For more information, please refer to this link:

Python String find() Method

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