Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- """
- Created on Fri Dec 02 14:14:14 2016
- @author: Howard
- """
- import email
- import getpass, imaplib
- import os
- import sys
- import datetime
- detach_dir = raw_input('Enter the path of folder: ')
- today = datetime.date.today().isoformat().replace('-','')
- timeStamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
- attachName = 'Attachments_' + today
- if attachName not in os.listdir(detach_dir):
- os.chdir(detach_dir)
- os.mkdir(attachName)
- userName = raw_input('Enter your GMail username: ')
- passwd = getpass.getpass('Enter your password: ')
- try:
- imapSession = imaplib.IMAP4_SSL('imap.gmail.com')
- typ, accountDetails = imapSession.login(userName, passwd)
- if typ != 'OK':
- print 'Not able to sign in!'
- raise
- imapSession.select('[Gmail]/All Mail')
- typ, data = imapSession.search(None, '(UNSEEN)')
- if typ != 'OK':
- print 'Error searching Inbox.'
- raise
- # Iterating over all emails
- for msgId in data[0].split():
- typ, messageParts = imapSession.fetch(msgId, '(RFC822)')
- if typ != 'OK':
- print 'Error fetching mail.'
- raise
- emailBody = messageParts[0][1]
- mail = email.message_from_string(emailBody)
- for part in mail.walk():
- if part.get_content_maintype() == 'multipart':
- #print part.as_string()
- continue
- if part.get('Content-Disposition') is None:
- #print part.as_string()
- continue
- fileName = part.get_filename().split('.')[0] + '_' + timeStamp + '.' +part.get_filename().split('.')[1]
- if bool(fileName):
- filePath = os.path.join(detach_dir, attachName, fileName)
- if not os.path.isfile(filePath) :
- print fileName
- fp = open(filePath, 'wb')
- fp.write(part.get_payload(decode=True))
- fp.close()
- imapSession.close()
- imapSession.logout()
- except :
- print 'Not able to download all attachments.'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement