Last active
October 19, 2019 23:19
-
-
Save erm3nda/b65bfd8a602ff610dccfdadae245891a to your computer and use it in GitHub Desktop.
read gmail imap email
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
#!/usr/bin/env python | |
# -*- coding:utf-8 -*- | |
import sys | |
import imaplib | |
import email | |
import datetime | |
import re | |
def process_mailbox(M): | |
diction = [] | |
rv, data = M.search(None, "ALL") | |
if rv != 'OK': | |
print('No messages found!') | |
return | |
for num in data[0].split()[0]: | |
rv, data = M.fetch(str(num), '(RFC822)') | |
if rv != 'OK': | |
print("ERROR getting message", num) | |
return | |
msg = email.message_from_bytes(data[0][1]) | |
hdr = email.header.make_header(email.header.decode_header(msg['Subject'])) | |
from_address = email.header.make_header(email.header.decode_header(msg['From'])) | |
msg_to = email.header.make_header(email.header.decode_header(msg['To'])) | |
PAT_EMAIL = re.compile(r"[0-9A-Za-z._-]+\@[0-9A-Za-z._-]+") | |
to_address = PAT_EMAIL.findall(str(msg_to))[0] | |
subject = str(hdr) | |
print('Message %s: %s - From: %s - To: %s' % (num, subject, from_address, to_address)) | |
date_tuple = email.utils.parsedate_tz(msg['Date']) | |
if date_tuple: | |
local_date = datetime.datetime.fromtimestamp(email.utils.mktime_tz(date_tuple)) | |
#print('Local Date:', local_date.strftime('%a, %d %b %Y %H:%M:%S')) | |
for part in msg.walk(): | |
if part.get_content_type() == 'text/html': | |
print(part.get_payload()) | |
diction.append(part.get_payload()) | |
if __name__ == "__main__": | |
imap_host = 'imap.gmail.com' | |
imap_user = 'username' | |
imap_pass = 'password' | |
M = imaplib.IMAP4_SSL(imap_host) | |
try: | |
rv, data = M.login(imap_user, imap_pass) | |
except imaplib.IMAP4.error as e: | |
print("LOGIN FAILED!") | |
print(str(e)) | |
sys.exit(1) | |
print(rv, data) | |
rv, mailboxes = M.list() | |
if rv == 'OK': | |
print('Mailboxes:') | |
print(mailboxes) | |
rv, data = M.select('Inbox') | |
if rv == 'OK': | |
print('Processing mailbox...\n') | |
process_mailbox(M) | |
M.close() | |
else: | |
print('ERROR: Unable to open mailbox', rv) | |
M.logout() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment