import email
import getpass, imaplib
import os
import sys, shutil
import datetime
import logging
##
## Variables to set
##
detach_dir = '/tmp'
archive_dir = 'archive'
userName = 'uuuu'
passwd = 'pppppppp'
mailserver='mail.mmmm.com'
# actual time and date
now = datetime.datetime.now()
if not os.path.isdir(detach_dir):
os.mkdir(detach_dir)
log_file=os.path.join(detach_dir,'imap.log')
logging.basicConfig(filename=log_file,format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger('imap')
logger.setLevel(logging.DEBUG)
if archive_dir not in os.listdir(detach_dir):
logger.warning('archive directory does not exist, crating one..')
os.mkdir(os.path.join(detach_dir,archive_dir))
# create logger
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)
# 'application' code
# logger.debug('debug message')
def get_attachments():
try:
# logging into account
logger.debug('username: %s, passwd: %s' %(userName,passwd))
imapSession = imaplib.IMAP4_SSL(mailserver)
typ, accountDetails = imapSession.login(userName, passwd)
logger.info('Logging answer: %s' % typ)
if typ != 'OK':
print 'Not able to sign in!'
raise
# open INBOX directory and search only for UNSEEN (unread) messages
imapSession.select('INBOX')
typ, data = imapSession.search(None, 'UNSEEN')
logger.debug('Opening INBOX directory answer: %s' % typ)
if typ != 'OK':
print 'Error searching Inbox.'
raise
# Iterating over all unseen emails
for msgId in data[0].split():
typ, messageParts = imapSession.fetch(msgId, '(RFC822)')
logger.debug('Fetching whole email message answer: %s' % typ)
if typ != 'OK':
print 'Error fetching mail.'
raise
emailBody = messageParts[0][1]
mail = email.message_from_string(emailBody)
# iterating over all attachments in email
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
# get the filename of attachment
fileName = part.get_filename()
logger.debug('I have found file: %s' % fileName)
if bool(fileName):
# full path to file where attachment should be saved
# filePath = os.path.join(detach_dir, 'archive', fileName)
filePath = os.path.join(detach_dir, fileName)
# move existing file to the archive
if os.path.isfile(filePath):
logger.debug('Moving old %s to %s dir.' % (fileName,archive_dir))
try:
deltatime = now - datetime.timedelta(days=7)
path_date = deltatime.strftime("%Y-%m-%d")
new_fileName = '%s_%s' % (path_date,fileName)
shutil.move(filePath,os.path.join(detach_dir,archive_dir,new_fileName))
except:
logger.error('Couldnt move %s to %s directory' % (fileName, archive_dir))
logger.info('Attachment %s will be saved as %s' % (fileName,filePath))
# 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()
return 0
except :
logger.error('Not able to download all attachments.')
return 1
if __name__ == '__main__':
logger.info('IMAP script session opened.')
get_attachments()
logger.info('IMAP script session closed.')
Comments