# Python 3.8.0 import smtplib import time import imaplib import email import traceback # ------------------------------------------------- # # Utility to read email from Gmail Using Python # # ------------------------------------------------ ORG_EMAIL = "service@choozmo.com" FROM_EMAIL = "service@choozmo.com" FROM_PWD = "meohmerayzyvrgdw" SMTP_SERVER = "imap.gmail.com" SMTP_PORT = 993 def ext_body(body): lines=body.split('\n') for l in lines: if 'To: ' in l[0:8]: return l.replace('To: ') def read_email_from_gmail(): try: mail = imaplib.IMAP4_SSL(SMTP_SERVER) mail.login(FROM_EMAIL,FROM_PWD) # mail.select('inbox') mail.select('[Gmail]/Spam') data = mail.search(None, 'ALL') mail_ids = data[1] id_list = mail_ids[0].split() first_email_id = int(id_list[0]) latest_email_id = int(id_list[-1]) for i in range(latest_email_id,first_email_id, -1): data = mail.fetch(str(i), '(RFC822)' ) for response_part in data: arr = response_part[0] if isinstance(arr, tuple): msg = email.message_from_string(str(arr[1],'utf-8')) print(msg) email_subject = msg['subject'] email_from = msg['from'] email_to = msg['to'] email_body = msg.get_payload(decode=True) # email_body = msg['body'] print('From : ' + email_from + '\n') print('To : ' + email_to + '\n') if email_body is not None: to_addr=str(ext_body(email_body)) if to_addr is not None: print(to_addr) # print('Body : ' + email_body + '\n') # print('Subject : ' + email_subject + '\n') except Exception as e: traceback.print_exc() print(str(e)) read_email_from_gmail()