Getting/Saving email attachments w/ poplib and email modules

brettk at gmail.com brettk at gmail.com
Tue Jun 21 18:59:03 EDT 2005


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()?

This is essentially what i'm doing now,

##############
import email
import poplib

mimes = ["image/tif","image/tiff","images/x-tif","image/x-tiff",
            "application/tif","application/tiff","application/x-tif",
            "application/x-tiff"]

def WriteAttachment(msg):
    docs = [(part.get_filename(),part.get_payload(decode=True))
            for part in msg.get_payload() if part.get_type() in mimes]
    for name,data in docs:
        f = file(name,'wb')
        f.write(data)
        f.close()

ms = poplib.POP3(server)
ms.user(uname)
ms.pass_(passw)

msgcount = len(ms.list()[1])
for i in range(msgcount):
    for j in ms.retr(i+1)[1]:
       msg = email.message_from_string(j)
       WriteAttachment(msg)

##################################

I'm sure i'm missing something pretty simple, i just need a slap in the
right direction...

TIA




More information about the Python-list mailing list