• Status: Solved
  • Priority: Low
  • Security: Public
  • Views: 73
  • Last Modified:

reading the text of an email using python

so i'm working on a school project in python for which the app needs to actively detect the presence of a email (with a specific subject but no specific sender). the app also needs to be able to read the email's body.  tutorials on the internet haven't helped too much. is there a way to do this passively(without hindering the rest of the code) using imap or poplib?
kshitij sawhney
kshitij sawhney
  • 2
1 Solution
Dr. KlahnPrincipal Software EngineerCommented:
Are you expected to handle HTML emails as well as plain text?  I would have to say that if the requirement is to handle HTML emails as well as plain text, the task is overly difficult.
kshitij sawhneyAuthor Commented:
it'll be plain text..
Flabio GatesCommented:
some old imaplib code I had:
import email, imaplib

host = 'some.imap4.server'
user = 'yourname'
passwd = 'secret'

messages = []
conn = imaplib.IMAP4(host)
conn.login(user, passwd)
    conn.select() # select the inbox
        ret, ids = conn.search(None, '(FROM "Somebody")')
        s = ids[0].strip()
        if s:
            ids = s.split()
            ids = []
        for id_ in ids:
            r, data = conn.fetch(id_, '(RFC822)')
            m = email.message_from_string(data[0][1])
            # m.get_payload() gives you the E-mail body
            messages.append((int(id_), m))

    finally: conn.close()
finally: conn.logout()

Open in new window

imaplib docs here.

some old poplib code I had:
import poplib, email

host = 'some.pop3.server'
user = 'yourname'
passwd = 'secret'

messages = []
conn = poplib.POP3_SSL(host)
    msgcount = conn.stat()[0]

    for i in range(1, msgcount+1):
        m = email.message_from_string('\n'.join(conn.retr(i)[1]))
        # m.get_payload() gives you the E-mail body
        messages.append((i, m))

finally: conn.quit()

Open in new window

poplib docs here.

I should warn you that the code is working on python 2.5 (I said it was old.)
The docs I linked to are for python 3.x.
Flabio GatesCommented:
Question inactive
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now