How to Download Outlook Attachment from Python Script

How to download outlook attachment from Python Script?

import email
import imaplib
import os

class FetchEmail():

connection = None
error = None
mail_server="host_name"
username="outlook_username"
password="password"
self.save_attachment(self,msg,download_folder)
def __init__(self, mail_server, username, password):
self.connection = imaplib.IMAP4_SSL(mail_server)
self.connection.login(username, password)
self.connection.select(readonly=False) # so we can mark mails as read

def close_connection(self):
"""
Close the connection to the IMAP server
"""
self.connection.close()

def save_attachment(self, msg, download_folder="/tmp"):
"""
Given a message, save its attachments to the specified
download folder (default is /tmp)

return: file path to attachment
"""
att_path = "No attachment found."
for part in msg.walk():
if part.get_content_maintype() == 'multipart':
continue
if part.get('Content-Disposition') is None:
continue

filename = part.get_filename()
att_path = os.path.join(download_folder, filename)

if not os.path.isfile(att_path):
fp = open(att_path, 'wb')
fp.write(part.get_payload(decode=True))
fp.close()
return att_path

def fetch_unread_messages(self):
"""
Retrieve unread messages
"""
emails = []
(result, messages) = self.connection.search(None, 'UnSeen')
if result == "OK":
for message in messages[0].split(' '):
try:
ret, data = self.connection.fetch(message,'(RFC822)')
except:
print "No new emails to read."
self.close_connection()
exit()

msg = email.message_from_string(data[0][1])
if isinstance(msg, str) == False:
emails.append(msg)
response, data = self.connection.store(message, '+FLAGS','\\Seen')

return emails

self.error = "Failed to retrieve emails."
return emails

Above code works for me to download attachment. Hope this really helpful for any one.

How to download email attachments from outlook using Python

Work with Items.Restrict Method (Outlook) to filter by subject line and attachment. see Filtering Items

import win32com.client

Outlook = win32com.client.Dispatch("Outlook.Application")
olNs = Outlook.GetNamespace("MAPI")
Inbox = olNs.GetDefaultFolder(6)

Filter = ("@SQL=" + chr(34) + "urn:schemas:httpmail:subject" +
chr(34) + " Like 'Snarf' AND " +
chr(34) + "urn:schemas:httpmail:hasattachment" +
chr(34) + "=1")

Items = Inbox.Items.Restrict(Filter)
for Item in Items:
for attachment in Item.Attachments:
print(attachment.FileName)
attachment.SaveAsFile(r"C:\\subfolder\\" + attachment.FileName")


Filtering Items Using a String Comparison that DASL filters support includes equivalence, prefix, phrase, and substring matching. Note that when you filter on the Subject property, prefixes such as "RE: " and "FW: " are ignored.

save outlook attachments with python

The wildcard for parameter subject wont work because parameter subject is used as string when comparing for equality in message.Subject == subject.

You could instead use string-method startswith on the message subject like message.Subject.startswith(subject_prefix)
and call your method with a common prefix like save_attachments('PB Report - ').

Furthermore use the attachment.FileName to construct the output-file path.

You could use GetLast() or Sort() with appropriate message property to filter on the newest sent report. Or you could parse the dates in message's subject and sort them accordingly. However this would deserve another question, own research and further specification and focus.

Solution

An example solution could be as follows (see comments for adjustments):

def save_attachments(subject_prefix): # changed parameter name
messages.Sort("[ReceivedTime]", True) # sort by received date: newest to oldest
for message in messages:
if message.Subject.startswith(subject_prefix): # changed test
print("saving attachments for:", message.Subject)
for attachment in message.Attachments:
print(attachment.FileName)
attachment.SaveAsFile(os.path.join(path, str(attachment.FileName))) # changed to file-name
return # exit after first matched message

Alternatively use GetLast() if you know the messages only contain desired ones, sorted by date.

message = messages.GetLast()
while message: # to test if there is a (last) message at all
# save attachment

Related questions

  • str.startswith with a list of strings to test for
  • Search the entire Outlook email box for specific emails using Python
  • How to go through Outlook emails in reverse order using Python

How download attachments from secondary outlook email by Python?

To access the shared inbox try the following

inbox = outlook.Folders["FiTeam@email.com"].Folders["Inbox"]

also you should fix ("D:\DownloadingEmail\\replenishment") to ("D:\\DownloadingEmail\\replenishment")


SaveAsFile(os.path.join(path, str(attachment) should be SaveAsFile(os.path.join(path, str(attachment.FileName)


message.Unread = False to message.UnRead


see my example code below-

import os
import win32com.client
path = os.path.expanduser("D:\\DownloadingEmail\\replenishment")
print(path)
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.Folders["FiTeam@email.com"].Folders["Inbox"]
messages = inbox.Items


def save_attachments(subject):
for message in messages:
if message.Subject.startswith(subject):

for attachment in message.Attachments:
attachment.SaveAsFile(os.path.join(path, str(attachment.FileName)))
if message.UnRead:
message.UnRead = False
continue


save_attachments('Replenishment')


Related Topics



Leave a reply



Submit