Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import ftplib
- import email
- import getpass, imaplib
- import os
- import sys
- EMAIL_HOST = 'imap.gmail.com'
- EMAIL_USERNAME = 'user'
- EMAIL_PASSWORD = 'password'
- FTP_HOST = 'ftp'
- FTP_USERNAME = 'someuser'
- FTP_PASSWORD = 'secret'
- ssl = True
- def upload(file,fileName):
- file_to_send = open(file,'rb') # file to send
- session.storbinary('STOR %s' % fileName, file) # send the file: sender_date_time.jpg
- file.close() # close file and FTP
- detach_dir = '.'
- if 'attachments' not in os.listdir(detach_dir):
- os.mkdir('attachments')
- try:
- imapSession = imaplib.IMAP4_SSL(EMAIL_HOST)
- typ, accountDetails = imapSession.login(EMAIL_USERNAME, EMAIL_PASSWORD)
- if typ != 'OK':
- print ('Not able to sign in!')
- raise
- imapSession.select('[Gmail]/All Mail')
- typ, data = imapSession.search(None, 'ALL')
- if typ != 'OK':
- print ('Error searching Inbox.')
- raise
- # Iterating over all emails
- for msgId in data[0].split(): # Split message id's and iterate
- typ, messageParts = imapSession.fetch(msgId, '(RFC822)') # Get seperate message
- if typ != 'OK':
- print ('Error fetching mail.')
- raise
- emailBody = messageParts[0][1]
- mail = email.message_from_string(emailBody) # Parse email payload
- sender = mail['From'] # Save sender name
- for part in mail.walk():
- if part.get_content_maintype() == 'multipart': # Check if email consists of multiple parts. Should be the case when an email has attachments as the regular email body is always present, + attachment = multipart
- print (part.as_string())
- continue
- if part.get('Content-Disposition') is None:
- print (part.as_string())
- continue
- if part.get('Content-Type') == 'image':
- continue
- print (part.get_filename()[len(part.get_filename()-4):len(part.get_filename())])
- if part.get_filename()[len(part.get_filename()-4):len(part.get_filename())] == '.jpg': # check if file is jpg file
- continue
- fileName = currentDateTime + sender + part.get_filename() # set filename, current date, sender and original file name
- upload(part.get_payload(decode=True),fileName) # upload fike to ftp server
- if bool(fileName): # write file to local file system
- filePath = os.path.join(detach_dir, 'attachments', fileName)
- if not os.path.isfile(filePath) :
- print (fileName)
- fp = open(filePath, 'wb')
- fp.write(part.get_payload(decode=True))
- fp.close()
- # Todo: set flags
- # imapsession.remove_flags(msgid,'UNSEEN') # Remove "unseen" flag
- # imapsession.add_flags(msgid,'SEEN') # Add "seen" flag
- imapSession.close()
- imapSession.logout()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement