Created
March 30, 2015 06:49
-
-
Save code-shoily/54c9e81b6214d4261412 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import imaplib | |
import email | |
from email.header import decode_header | |
import HTMLParser | |
IMAP_ADDR = 'imap.gmail.com' | |
USERNAME = '<EMAIL_ADDRESS>' | |
PASSWORD = '<PASSWORD>' | |
_parser = HTMLParser.HTMLParser() | |
def _decode_header(value): | |
if value.startswith('"=?'): | |
value = value.replace('"', '') | |
value, encoding = decode_header(value)[0] | |
if encoding: | |
value = value.decode(encoding) | |
return _parser.unescape(value) | |
def list_mails(addr=IMAP_ADDR, user=USERNAME, password=PASSWORD): | |
mailbox = imaplib.IMAP4_SSL(addr) | |
mailbox.login(user, password) | |
selected = mailbox.select('INBOX') | |
assert selected[0] == 'OK' | |
message_count = int(selected[1][0]) | |
for i in range(message_count, message_count-4, -1): | |
# ATTN: message_count - 4 = LAST FOUR MESSAGES, 0 = ALL MESSAGES etc | |
response = mailbox.fetch(str(i), '(RFC822)')[1] | |
for part in response: | |
if isinstance(part, tuple): | |
m = email.message_from_string(part[1]) | |
if m.get_content_maintype() == 'multipart': | |
for part in m.walk(): | |
if part.get_content_maintype() == 'multipart': continue | |
if part.get('Content-Disposition') is None: continue | |
filename = part.get_filename() | |
fp = open(filename, 'wb') | |
fp.write(part.get_payload(decode=True)) | |
fp.close() | |
print '%s saved!' % filename | |
mailbox.store(str(i), '+FLAGS', '\\Deleted') | |
yield {h: _decode_header(m[h]) for h in ('subject', 'from', 'date')} | |
mailbox.expunge() | |
mailbox.logout() | |
if __name__ == '__main__': | |
print "And the downloading begins... ;)" | |
for message in list_mails(): | |
print '-' * 40 | |
for h, v in message.items(): | |
print u'{0:8s}: {1}'.format(h.upper(), v) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment