Getting/Saving email attachments w/ poplib and email modules

Mike Meyer mwm at
Wed Jun 22 14:44:29 CEST 2005

brettk at writes:

> Hello All,
> Here's what I'm trying to do:
> I need to connect to a pop3 server, download all messages, and copy all
> of the attachments into a specific directory.  The actual email message
> is unimportant.  Now, I've found plenty of examples that strip the
> attachments from an email message, but most (if not all) of them take a
> file parameter.  My question is this:
> How can i retrieve an email message via poplib and pass it to
> email.message_from_string()?

A quick look at the poplib documentation shows the retr method, which gets
a message by number, and returns a list: ['response', ['line', ...], octets].

So to get a string, you'd do:

from poplib import POP3
from sys import exit

p = POP3('')
# authentication, etc.
msg_list = p.list()
if not msg_list.startswith('+OK'):
        # Handle error in listings

for msg in msg_list[1]:
        msg_num, _ = msg.split()
        resp = p.retr(msg_num)
        if resp.startswith('+OK'):
                # Deal with error retrieving message.

This is untested code, but the details of dealing with poplib should
be right.

Mike Meyer <mwm at>
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.

More information about the Python-list mailing list