Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bechampion/514077937bc8596beda9e7ceed083775 to your computer and use it in GitHub Desktop.
Save bechampion/514077937bc8596beda9e7ceed083775 to your computer and use it in GitHub Desktop.
import email
import getpass, imaplib
import os
import sys
imaplib._MAXLINE = 9999999
acc = sys.argv[1]
year = sys.argv[2]
path = "attachments-%s-%s" % ( acc , year)
detach_dir = '.'
if path not in os.listdir(detach_dir):
os.mkdir(path)
if acc == "uk":
userName = "garciaj.uk@gmail.com"
passwd = ""
if acc == "ar":
userName = "garciaj@gmail.com"
passwd = ""
imapSession = imaplib.IMAP4_SSL('imap.gmail.com')
typ, accountDetails = imapSession.login(userName, passwd)
if typ != 'OK':
print 'Not able to sign in!'
raise
print imapSession.list()
imapSession.select('[Gmail]/All Mail')
print '(SINCE "01-Jan-%s" BEFORE "01-Jan-%s" TO "%s")' % (str(int(year)-1),year,userName)
typ, data = imapSession.search(None, '(SINCE "01-Jan-%s" BEFORE "01-Jan-%s" TO "%s")' % (str(int(year)-1),year,userName))
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)
print msgId,
print " >> ",
print str(mail['From']),
print " >> ",
print str(mail['Date'])
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
try:
fileName = str(part.get_filename()).replace(" ","")
if bool(fileName):
filePath = os.path.join(detach_dir, path , fileName)
if not os.path.isfile(filePath) :
if fileName.lower().endswith(('.png', '.jpg', '.jpeg','JPG','JPEG' )):
print " >> ",
print fileName
fp = open(filePath, 'wb')
try:
fp.write(part.get_payload(decode=True))
except:
pass
fp.close()
os.popen("kitty +kitten icat %s/%s" % (path, fileName),'r', 1)
except:
pass
imapSession.close()
imapSession.logout()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment