0% found this document useful (0 votes)
76 views

Python-Download Attachment From Email Template

This Python class allows fetching emails from an IMAP server. It contains methods to connect to the server using a username and password, save any attachments found in messages to a download folder, retrieve unread messages and mark them as read, and close the connection. The fetch_unread_messages method searches for unread messages, downloads their content, and returns a list of email objects.

Uploaded by

Marco Rodriguez
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
76 views

Python-Download Attachment From Email Template

This Python class allows fetching emails from an IMAP server. It contains methods to connect to the server using a username and password, save any attachments found in messages to a download folder, retrieve unread messages and mark them as read, and close the connection. The fetch_unread_messages method searches for unread messages, downloads their content, and returns a list of email objects.

Uploaded by

Marco Rodriguez
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

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 retreive emails."


return emails

You might also like