I am trying to receive with Python the emails that I have in my Gmail. I connect without problems to my account and I get the mail from the one who sent the message, the subject or the delivery time, but there is no way to get the body of the message. I leave here my code and I explain:
import smtplib
import time
import imaplib
import email
def read_email_from_gmail():
try:
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('[email protected]','micontraseña')
mail.select('inbox')
type, 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])
for i in range(latest_email_id,first_email_id, -1):
typ, data = mail.fetch(i, '(RFC822)' )
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_date = msg['Date']
email_body = msg['body']
print 'From : ' + email_from + '\n'
print 'Subject : ' + email_subject + '\n'
print 'Date : ' + email_date + '\n'
print 'Body : ' + email_body + '\n'
except Exception, e:
print "Exception"
read_email_from_gmail()
As you can see, for example, I get the date with msg['Date']
, but I do not get something that returns the body of the message. I've tried Body and main, and I can not think of anything else. Thanks in advance.
******** Update September 11 ************
I have updated the code as you told me, now I am closer, but still missing things.
import smtplib
import time
import imaplib
import email
def read_email_from_gmail():
try:
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('[email protected]','isurki2230')
mail.select('inbox')
type, 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])
for i in range(latest_email_id,first_email_id, -1):
typ, data = mail.fetch(i, '(RFC822)' )
for response_part in data:
if isinstance(response_part, tuple):
msg = email.message_from_string(response_part[1])
if msg.is_multipart():
for part in msg.walk():
if part.get_content_type() in ("text/plain", "text/html"):
print(part.get_payload(decode = True))
else:
print(part.get_payload(decode = True))
except Exception, e:
print "\n"
read_email_from_gmail()
With that code this is the output I get:
This is a test #Aqui shows me a strange square
This is a test
#Aqui the message appears again, but with several html things like div and br, but when writing it in StackOverflow they do not appear. Can the code be "cleaned" a little more? Thanks.