0

This is my Python code to read an email:

import imaplib

mailserver=imaplib.IMAP4_SSL('imap.gmail.com',993)
user = 'm****l@gmail.com'
passs = 'm****s'
mailserver.login(user,passs)

status, count = mailserver.select('Inbox')
status, data = mailserver.fetch(count[0],'(UID BODY[TEXT])')

print(data)

mailserver.close()
mailserver.logout() 

It prints out the whole html portion of the message. How do I only print out the message itself?

user2883071
  • 960
  • 1
  • 20
  • 50
  • Walk the message object tree - http://stackoverflow.com/questions/1463074/how-can-i-get-an-email-messages-text-content-using-python – user3286261 May 04 '14 at 05:15

2 Answers2

0
import imaplib

mailserver=imaplib.IMAP4_SSL('imap.gmail.com',993)
user = 'm****l@gmail.com'
passs = 'm****s'
mailserver.login(user,passs)

status, count = mailserver.select('Inbox')
status, data = mailserver.fetch(count[0],'(RFC822)')

print(data)

# Something like this
import email
msg = email.message_from_string(data[0][1])
print(msg['Subject'], msg['Body'])

mailserver.close()
mailserver.logout() 

I posted a self reminder in a gist if you are curious.

https://gist.github.com/jmunsch/11374042

jmunsch
  • 22,771
  • 11
  • 93
  • 114
  • This is wrong. Using hardcoded offsets will fail, sooner or later. – Jan Kundrát May 05 '14 at 17:31
  • Thanks for pointing this out I didn't know that ... I think the docs might need some expanding .... https://docs.python.org/2/library/imaplib.html#imap4-example – jmunsch May 05 '14 at 22:51
0

This is a duplicate of How can I get an email message's text content using python? (among a ton of others). In short, you have to take a look at the MIME tree and find out which of these parts is interesting for you. Using a unversal offset like [1] will not work.

Community
  • 1
  • 1
Jan Kundrát
  • 3,700
  • 1
  • 18
  • 29