Last active
October 20, 2018 11:30
-
-
Save vadimkantorov/3007144 to your computer and use it in GitHub Desktop.
Backups all GMail emails+attachments from a given label AND from a given sender.
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
import argparse | |
import imaplib | |
import email | |
import os | |
parser = argparse.ArgumentParser(description = 'Backup GMail mailbox. Turn on less secure apps before running https://www.google.com/settings/security/lesssecureapps') | |
parser.add_argument('--username', required = True) | |
parser.add_argument('--password', required = True) | |
parser.add_argument('-o', default = '.') | |
parser.add_argument('--label', default = 'INBOX') | |
parser.add_argument('--to') | |
parser.add_argument('--content', action = 'store_true') | |
parser.add_argument('--addresses', action = 'store_true') | |
args = parser.parse_args() | |
gmail = imaplib.IMAP4_SSL('imap.gmail.com', 993) | |
gmail.login(args.username, args.password) | |
gmail.select(args.label) | |
search = gmail.search(None, '(TO "{}")'.format(args.to) if args.to else '') | |
for email_id in search[1][0].split(): | |
resp, data = gmail.fetch(email_id, '(RFC822)') | |
mail = email.message_from_string(data[0][1]) | |
email_dir = os.path.join(args.o, email_id) | |
if args.addresses: | |
print(mail['From'], mail['To'], mail.keys()) | |
if args.content: | |
if not os.path.exists(email_dir): | |
os.makedirs(email_dir) | |
with open(os.path.join(email_dir, 'email.txt'), 'w') as f: | |
f.write(str(mail).decode("quoted-printable")) | |
if mail.get_content_maintype() != 'multipart': | |
continue | |
for part in mail.walk(): | |
if part.get_content_maintype() == 'multipart': | |
continue | |
if part.get('Content-Disposition') is None: | |
continue | |
continue | |
filename = part.get_filename() | |
counter = 1 | |
if not filename: | |
filename = 'part-{:03d}{}'.format(counter, 'bin') | |
counter += 1 | |
attachment_path = os.path.join(email_dir, filename) | |
if not os.path.isfile(attachment_path): | |
with open(attachment_path, 'wb') as f: | |
f.write(part.get_payload(decode = True)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment