Skip to content

Instantly share code, notes, and snippets.

@gra
Created June 24, 2020 14:22
Show Gist options
  • Save gra/6be005a3c234abb73a29173ecf85db0f to your computer and use it in GitHub Desktop.
Save gra/6be005a3c234abb73a29173ecf85db0f to your computer and use it in GitHub Desktop.
Download / Upload eml files from Gmail IMAP
import sys
import imaplib
import email
ACCOUNT = ""
PASSWORD = ""
INBOX = "INBOX"
TRASH = "[Gmail]/Trash"
FILE = "modify.eml"
def main(argv):
M = imaplib.IMAP4_SSL('imap.gmail.com')
M.debug = 4
try:
rv, data = M.login(ACCOUNT, PASSWORD)
except imaplib.IMAP4.error as e:
print("LOGIN FAILED")
sys.exit(1)
rv, data = M.select(INBOX)
if rv == 'OK':
if argv[1] == "upload":
print("UPLOAD EMAIL")
f = open(FILE, "r")
msg = email.message_from_file(f)
f.close()
M.append("INBOX", "(\\Seen)", None, msg.as_bytes())
if argv[1] == "download":
print("DOWNLOAD EMAIL")
rv, data = M.search(None, "ALL")
if rv != 'OK':
print("No messages found!")
return
for num in data[0].split():
rv, data = M.fetch(num, '(RFC822)')
f = open(FILE, "wb")
f.write(data[0][1])
f.close()
M.close()
else:
print("ERROR: Unable to open mailbox ", rv)
M.logout()
if __name__ == "__main__":
main(sys.argv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment