Created
September 1, 2020 07:41
-
-
Save philshem/4ee388f7dc045366c16eb9730ca630a9 to your computer and use it in GitHub Desktop.
refactor stackoverflow answer to read unread emails and also fix for loop https://stackoverflow.com/a/53827775/2327328
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 imaplib | |
import email | |
# adapted from: https://stackoverflow.com/a/53827775/2327328 | |
def read_email_from_gmail(): | |
mail = imaplib.IMAP4_SSL('imap.gmail.com') | |
mail.login('MYEMAIL','MYSECRET') | |
mail.select('inbox') | |
result, data = mail.search(None, '(UNSEEN)') | |
mail_ids = data[0] | |
id_list = mail_ids.split() | |
for _, i in enumerate(id_list): | |
# need str(int(i)) | |
result, data = mail.fetch(str(int(i)), '(RFC822)' ) | |
for response_part in data: | |
if isinstance(response_part, tuple): | |
# from_bytes, not from_string | |
msg = email.message_from_bytes(response_part[1]) | |
email_subject = msg['subject'] | |
email_from = msg['from'] | |
print ('From : ' + email_from + '\n') | |
print ('Subject : ' + email_subject + '\n') | |
# nothing to print here | |
read_email_from_gmail() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment