Created
July 10, 2018 00:02
-
-
Save darachm/a17a7a96ea3da992380d8528055b5c64 to your computer and use it in GitHub Desktop.
python3 script to yank down emails from gmail with imap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# modified from this: https://gist.github.com/baali/2633554/ | |
# Same logic, etc, just modified for python3 | |
# Could use argument parser, but really how many times are you going to use this? | |
# | |
# Something in lines of http://stackoverflow.com/questions/348630/how-can-i-download-all-emails-with-attachments-from-gmail | |
# Make sure you have IMAP enabled in your gmail settings. | |
import getpass | |
import imaplib | |
import os | |
outdir = "/mnt/gmail/" # set to where you want them to go | |
if not os.path.isdir(outdir): | |
os.mkdir(outdir) | |
userName = input('Enter your GMail username: ') | |
passwd = getpass.getpass('Enter your password: ') | |
start_from_where = 0 # this is incase you get interrupted | |
basename = "all" | |
try: | |
print("gonna login as "+userName) | |
imapSession = imaplib.IMAP4_SSL('imap.gmail.com') | |
typ, accountDetails = imapSession.login(userName, passwd) | |
print("login says : "+typ) | |
if typ != 'OK': | |
print('Not able to sign in!') | |
raise | |
imapSession.select("\"[Gmail]/All Mail\"") | |
print("selected all mail") | |
typ, data = imapSession.search(None, "ALL") | |
print("search says : "+typ) | |
if typ != 'OK': | |
print('Error searching Inbox.') | |
raise | |
for msgId in data[0].split(): | |
if int(msgId.decode("utf-8")) < start_from_where : | |
continue | |
typ, messageParts = imapSession.fetch(msgId, '(RFC822)') | |
if typ != 'OK': | |
print('Error fetching mail.') | |
raise | |
print("writing "+msgId.decode("utf-8")+" to "+ | |
outdir+"all."+msgId.decode("utf-8")+".rfc822") | |
with open(outdir+basename+"."+msgId.decode("utf-8")+".rfc822",'w') as f: | |
f.write(messageParts[0][1].decode("latin_1")) | |
imapSession.close() | |
imapSession.logout() | |
except: | |
print("ERK i dunno something broke") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment