Getting/Saving email attachments w/ poplib and email modules

Tim Williams tdw at tdw.net
Wed Jun 22 07:17:51 EDT 2005


----- Original Message ----- 
From: <brettk at gmail.com>
> 
> 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

##############
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):
    for part in msg.walk():
        if part.get_type() in mimes:
            name = part.get_filename()
            data = part.get_payload(decode=True)
            f = file(name,'wb')
            f.write(data)
            f.close()

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

msgcount = len(ms.list()[1])
for i in range(msgcount):
    response, msg_as_list, size = ms.retr(i+1)
    msg = email.message_from_string('\r\n'.join(msg_as_list))
    WriteAttachment(msg)

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



More information about the Python-list mailing list