Guest User

Untitled

a guest
Dec 9th, 2019
398
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import smtplib
  2. import time
  3. import imaplib
  4. import email
  5.  
  6. ORG_EMAIL   = "@gmail.com"
  7. FROM_EMAIL  = "YourEmail" + ORG_EMAIL
  8. FROM_PWD    = "Your password"
  9. SMTP_SERVER = "imap.gmail.com"
  10. SMTP_PORT   = 993
  11.  
  12. def read_email_from_gmail():
  13.     try:
  14.         mail = imaplib.IMAP4_SSL(SMTP_SERVER)
  15.         mail.login(FROM_EMAIL,FROM_PWD)
  16.         mail.select('inbox')
  17.  
  18.         type, data = mail.search(None, 'ALL')
  19.         mail_ids = data[0]
  20.  
  21.         id_list = mail_ids.split()  
  22.         first_email_id = int(id_list[0])
  23.         latest_email_id = int(id_list[-1])
  24.  
  25.  
  26.         for i in range(latest_email_id,first_email_id, -1):
  27.             typ, data = mail.fetch(i, '(RFC822)' )
  28.  
  29.             for response_part in data:
  30.                 if isinstance(response_part, tuple):
  31.                     msg = email.message_from_string(response_part[1])
  32.                     email_subject = msg['subject']
  33.                     email_from = msg['from']
  34.                     print('From : {}'.format(email_from))
  35.                     print('Subject : {}'.format(email_subject))
  36.  
  37.     except Exception as e:
  38.         print(e)
  39.  
  40. if __name__ == '__main__':
  41.     read_email_from_gmail()
RAW Paste Data