Skip to content

Instantly share code, notes, and snippets.

@hollanddd
Last active August 29, 2015 13:55
Show Gist options
  • Save hollanddd/8712059 to your computer and use it in GitHub Desktop.
Save hollanddd/8712059 to your computer and use it in GitHub Desktop.
fetches email attachments
import imaplib, email
def fetch_csv_from_email(self):
file_name_list = []
detatch_dir = '.'
if 'files' not in os.listdir(detatch_dir):
os.mkdir('files')
mail_session = imaplib.IMAP4_SSL('your_mail_box')
typ, account_details = mail_session.login('username', 'psswd')
if typ != 'OK':
print 'Error trying to sign in'
raise
mail_session.select('inbox')
typ, data = mail_session.search(None, 'ALL')
if typ != 'OK':
print 'error search inbox'
raise
for msg_id in data[0].split():
typ, message_parts = mail_session.fetch(msg_id, '(RFC822)')
if typ != 'OK':
print 'error fetching message'
raise
msg_body = message_parts[0][1]
mail = email.message_from_string(msg_body)
for part in mail.walk():
if part.get_content_maintype() == 'multipart':
continue
if part.get('Content-Disposition') is None:
continue
file_name = part.get_filename()
# stub cleanup
name_parts = file_name.split('.')
if len(name_parts) >= 3:
file_name = name_parts[0] + '.csv'
if bool(file_name):
file_path = os.path.join(detatch_dir, 'files', file_name)
if not os.path.isfile(file_path):
file_name_list.append(file_name)
fp = open(file_path, 'wb')
fp.write(part.get_payload(decode=True))
fp.close()
# mark for delete
mail_session.store(msg_id, '+FLAGS', '\\Deleted')
# clear out deleted messages
mail_session.expunge()
mail_session.close()
mail_session.logout()
#return file_name_list
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment