Posts: 7
Joined: Sun Oct 28, 2012 5:54 pm

Displaying Email Messages

Sun Nov 04, 2012 11:45 pm

Okay! So I want to display the contents of the latest email in python. Here's my code

Code: Select all

import poplib
from email import parser
mailserver = poplib.POP3_SSL('pop.gmail.com')
mailserver.user('recent:daitomodachi6') #use 'recent mode'
mailserver.pass_('password') #consider not storing in plaintext!
msg = mailserver.retr(1)
print msg
All I want to do is display the message of my recent email in my mailbox. However, I keep getting weird message
message by Coolcapengineer, on Flickr

Posts: 288
Joined: Sat Aug 04, 2012 8:28 am
Contact: Website

Re: Displaying Email Messages

Mon Nov 05, 2012 1:49 pm

`poplib` gives you the message in source form, as it is stored in mailbox files. `msg` is a list with three elements: The status answer from the server, the mail source as a sequence of lines, and the size of the message in bytes. You have to parse and decode the message, or at least the parts you want to display. That's what the stuff in the `email` package in the Python standard library is meant for.

E-Mails are not that simple. It is a possibly nested, i.e. tree like, structure of message parts. The format is described in RFC 2822 for the headers and RFC 2045… for the content.

Your example seems to be containing a word processor file as attachment.

Code: Select all

while not self.asleep():
    sheep += 1

Posts: 517
Joined: Wed Oct 10, 2012 6:20 am
Location: Switzerland

Re: Displaying Email Messages

Mon Nov 05, 2012 2:32 pm

As BlackJack said, you have an email with an attachment, which is mime encoded.

Basically when you send an email with an attachment, it gets encoded to plain text and then put into the body of the email. When you read an email, your email client reads the message, recognizes that there are encoded attachments and then decodes them and displays them as "attachments" which you can then save and use as whatever they were originally, .doc, .jpg, etc.

You will need to use Python to do the same thing. It will have to recognize that there are attachments and decode them and save them out to the file system.

Luckily the email library in python seems set up to do this, it will scan the whole message, figure out how many attachments there are (how many "parts", each attachment is a part) and then let you loop over the parts to decode and save them.

But if all you want is the body of the email messages, you can skip the part where it loops and decodes the attachments.

Here are a couple of examples of using python to decode multi part email messages, I haven't looked at them in detail to see what you would need to not do if you did not want the attachments decoded, but I bet you can figure it out.

http://code.activestate.com/recipes/866 ... ack-a-mul/

Return to “Python”

Who is online

Users browsing this forum: louiepi, paddyg and 24 guests