Skip navigation

Tag Archives: Gmail

import email, getpass, imaplib, os

detach_dir = '.'

### directory where to save attachments (default: current)

m = imaplib.IMAP4_SSL('imap.gmail.com', 993)
m.login('username@gmail.com','password')
keywordsSearch = 'bananas oranges'
searchString = "(ALL SUBJECT '%s')" % keywordsSearch

### m.search(None, "(ALL SUBJECT 'bananas oranges')")
resp, items = m.search(None, searchString)
items = items[0].split()
for emailid in items:
    resp, data = m.fetch(emailid, "(RFC822)")
    email_body = data[0][1]
    mail = email.message_from_string(email_body)
    if mail.get_content_maintype() != 'multipart':
        continue
    print "["+mail["From"]+"] :" + mail["Subject"]
    for part in mail.walk():
        if part.get_content_maintype() == 'multipart':
            continue
        if part.get('Content-Disposition') is None:
            continue
        filename = part.get_filename()
        counter = 1
        if not filename:
            filename = 'part-%03d%s' % (counter, 'bin')
            counter += 1
        att_path = os.path.join(detach_dir, filename)
        if not os.path.isfile(att_path) :
            fp = open(att_path, 'wb')
            fp.write(part.get_payload(decode=True))
            fp.close()

Advertisements

You can send more than 500 emails per day by using Google’s recommendation of creating more than one account for sending.

Read More »