Skip to content

Instantly share code, notes, and snippets.

@chand1012
Created April 3, 2017 19:05
Show Gist options
  • Save chand1012/024a2fc4001744f64bbb8b7e9ebd36c5 to your computer and use it in GitHub Desktop.
Save chand1012/024a2fc4001744f64bbb8b7e9ebd36c5 to your computer and use it in GitHub Desktop.
import imaplib
import email
from json import loads
def email_login_info(file_name='login.json'):
try:
file_keys = open(file_name)
except:
file_keys = open(file_name, 'w')
raw_json = '''{
"email":"",
"password"
}
'''
print("Error! JSON file does not exist!")
parsed_json = loads(file_keys.read())
return parsed_json
FROM_EMAIL = email_login_info()['email']
FROM_PWD = email_login_info()['password']
SMTP_SERVER = "imap.gmail.com"
SMTP_PORT = 993
mail = imaplib.IMAP4_SSL(SMTP_SERVER)
mail.login(FROM_EMAIL,FROM_PWD)
mail.select('inbox')
etype, data = mail.search(None, 'ALL')
mail_ids = data[0]
id_list = mail_ids.split()
first_email_id = int(id_list[0])
latest_email_id = int(id_list[-1])
print(str(first_email_id) + ' ' + str(latest_email_id))
typ, data = mail.fetch(latest_email_id, '(RFC822)' ) # i is the email id
for response_part in data:
if isinstance(response_part, tuple):
msg = email.message_from_string(response_part[1])
email_subject = msg['subject']
email_from = msg['from']
email_msg = msg
print 'From : ' + email_from + '\n'
print 'Subject : ' + email_subject + '\n'
try:
for body in msg.get_payload():
print body.get_payload()
except:
print msg.get_payload()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment