Get attachments with Python over IMAP

This comes from the old blog:

I’m currently working on some stuff for my blog, well, not exactly this blog, another, I guess it may be better to sometimes post via email, sometimes just test, sometimes images. This is what I’ve got so far.

# @author    Marco Antonio Islas Cruz <markuz@islascruz.org>
# @copyright 2011 Marco Antonio Islas Cruz
# @license   http://www.gnu.org/licenses/gpl.txt
 
import imaplib
import email
imaplib.IMAP4.debug = imaplib.IMAP4_SSL.debug = 1
 
username,passwd = ('usuario','password')
 
con = imaplib.IMAP4_SSL('host',993)
con.login(username, passwd)
con.select()
typ, data = con.search(None, '(UNSEEN)')
c = 0
for num in data[0].split():
    typ, data = con.fetch(num, '(RFC822)')
    c +=1
    text = data[0][1]
    msg = email.message_from_string(text)
    for part in msg.walk():
        if part.get_content_maintype() == 'multipart':
            continue
        if part.get('Content-Disposition') is None:
            continue
        filename = part.get_filename()
        data = part.get_payload(decode=True)
        if not data:
            continue
        f  = open(os.join(os.environ['HOME'],filename), 'w')
        f.write(data)
        f.close()
        
con.close()
con.logout()

 

The code is available under the GPL license. You can follow this script (if it ever evolves) in github.

Loading