# -*- coding: utf-8 -*-
"""
Created on Fri Feb  9 13:38:04 2018

@author: Shirshendu
"""
import email
import imaplib
#import email
sender_email='shirsaha@in.ibm.com'
mail = imaplib.IMAP4_SSL('imap.gmail.com')
#mail= imaplib.IMAP4_SSL('oop.uk.relay.ibm.com')
mail.login('mail.shirshendu@gmail.com', 'GM@!l.c0m')
#mail.login('shirsaha@in.ibm.com', 'Pyth0n@!NLP')
mail.select('inbox')
resp, items = mail.search(None, 'FROM', '"%s"' % sender_email)
#for m in items[0].split():
#    resp, items = mail.fetch(m,"(BODY[HEADER.FIELDS (FROM)])")
##                             '(RFC822)')
#    body = 'Message %s\n%s\n' % (m, items[0][1])
#    msg = email.message_from_string(body)
##    email.utils.parseaddr(address)
#    print(msg['From'])
#    print(msg.get_payload(decode=True))
#mail.close()
#mail.logout()




for id in items[0].split():
	status, data = mail.fetch(id, '(RFC822)')

	email_msg = email.message_from_bytes(data[0][1])

	#Print all the Attributes of email message like Subject,
	#print email_msg.keys()

	subject = email_msg['Subject']
	sender_email =  email_msg['From']
	sent_to_email =  email_msg['To']

	for part in email_msg.walk():
		if part.get_content_type() == 'text/plain':
			email_content = part.get_payload() # prints the raw text
			#TODO :
			#process_email() #Delete, Mark as Spam, Forward it
			#TODO :
#         print(subject) 
			print(email_content)

	




#mail.list()
## Out: list of "folders" aka labels in gmail.
#mail.select("inbox") # connect to inbox.
#result, data = mail.search(None, "ALL")
# 
##ids = data[0] # data is a list.
##id_list = ids.split() # ids is a space separated string
##latest_email_id = id_list[-1] # get the latest
## 
##result, data = mail.fetch(latest_email_id, "(RFC822)") # fetch the email body (RFC822) for the given ID
# 
##raw_email = data[0][1] # here's the body, which is raw text of the whole email
## including headers and alternate payloads
#print(raw_email)
#import getpass, imaplib
#
#M = imaplib.IMAP4()
#M.login(getpass.getuser(), getpass.getpass())
#M.select()
#typ, data = M.search(None, 'ALL')
#for num in data[0].split():
#    typ, data = M.fetch(num, '(RFC822)')
#    print 'Message %s\n%s\n' % (num, data[0][1])
#M.close()
#M.logout()