s4ros

IMAP attachments download

Nov 26th, 2016
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.32 KB | None | 0 0
  1. import email
  2. import getpass, imaplib
  3. import os
  4. import sys, shutil
  5. import datetime
  6. import logging
  7.  
  8. ##
  9. ## Variables to set
  10. ##
  11. detach_dir = '/tmp'
  12. archive_dir = 'archive'
  13. userName = 'uuuu'
  14. passwd = 'pppppppp'
  15. mailserver='mail.mmmm.com'
  16.  
  17. # actual time and date
  18. now = datetime.datetime.now()
  19.  
  20. if not os.path.isdir(detach_dir):
  21.     os.mkdir(detach_dir)
  22.  
  23. log_file=os.path.join(detach_dir,'imap.log')
  24. logging.basicConfig(filename=log_file,format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  25. logger = logging.getLogger('imap')
  26. logger.setLevel(logging.DEBUG)
  27.  
  28. if archive_dir not in os.listdir(detach_dir):
  29.     logger.warning('archive directory does not exist, crating one..')
  30.     os.mkdir(os.path.join(detach_dir,archive_dir))
  31.  
  32. # create logger
  33.  
  34. # create console handler and set level to debug
  35. ch = logging.StreamHandler()
  36. ch.setLevel(logging.DEBUG)
  37.  
  38. # create formatter
  39. formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  40.  
  41. # add formatter to ch
  42. ch.setFormatter(formatter)
  43.  
  44. # add ch to logger
  45. logger.addHandler(ch)
  46.  
  47. # 'application' code
  48. # logger.debug('debug message')
  49.  
  50.  
  51. def get_attachments():
  52.     try:
  53.         # logging into account
  54.         logger.debug('username: %s, passwd: %s' %(userName,passwd))
  55.         imapSession = imaplib.IMAP4_SSL(mailserver)
  56.         typ, accountDetails = imapSession.login(userName, passwd)
  57.         logger.info('Logging answer: %s' % typ)
  58.         if typ != 'OK':
  59.             print 'Not able to sign in!'
  60.             raise
  61.  
  62.         # open INBOX directory and search only for UNSEEN (unread) messages
  63.         imapSession.select('INBOX')
  64.         typ, data = imapSession.search(None, 'UNSEEN')
  65.         logger.debug('Opening INBOX directory answer: %s' % typ)
  66.         if typ != 'OK':
  67.             print 'Error searching Inbox.'
  68.             raise
  69.  
  70.         # Iterating over all unseen emails
  71.         for msgId in data[0].split():
  72.             typ, messageParts = imapSession.fetch(msgId, '(RFC822)')
  73.             logger.debug('Fetching whole email message answer: %s' % typ)
  74.             if typ != 'OK':
  75.                 print 'Error fetching mail.'
  76.                 raise
  77.  
  78.             emailBody = messageParts[0][1]
  79.             mail = email.message_from_string(emailBody)
  80.             # iterating over all attachments in email
  81.             for part in mail.walk():
  82.                 if part.get_content_maintype() == 'multipart':
  83.                     # print part.as_string()
  84.                     continue
  85.                 if part.get('Content-Disposition') is None:
  86.                     # print part.as_string()
  87.                     continue
  88.                 # get the filename of attachment
  89.                 fileName = part.get_filename()
  90.                 logger.debug('I have found file: %s' % fileName)
  91.  
  92.                 if bool(fileName):
  93.                     # full path to file where attachment should be saved
  94.                     # filePath = os.path.join(detach_dir, 'archive', fileName)
  95.                     filePath = os.path.join(detach_dir, fileName)
  96.                     # move existing file to the archive
  97.                     if os.path.isfile(filePath):
  98.                         logger.debug('Moving old %s to %s dir.' % (fileName,archive_dir))
  99.                         try:
  100.                             deltatime = now - datetime.timedelta(days=7)
  101.                             path_date = deltatime.strftime("%Y-%m-%d")
  102.                             new_fileName = '%s_%s' % (path_date,fileName)
  103.                             shutil.move(filePath,os.path.join(detach_dir,archive_dir,new_fileName))
  104.                         except:
  105.                             logger.error('Couldnt move %s to %s directory' % (fileName, archive_dir))
  106.                     logger.info('Attachment %s will be saved as %s' % (fileName,filePath))
  107.                     # if not os.path.isfile(filePath) :
  108.                     # print fileName
  109.                     fp = open(filePath, 'wb')
  110.                     fp.write(part.get_payload(decode=True))
  111.                     fp.close()
  112.         imapSession.close()
  113.         imapSession.logout()
  114.         return 0
  115.     except :
  116.         logger.error('Not able to download all attachments.')
  117.         return 1
  118.  
  119. if __name__ == '__main__':
  120.     logger.info('IMAP script session opened.')
  121.     get_attachments()
  122.     logger.info('IMAP script session closed.')
Add Comment
Please, Sign In to add comment