#!/usr/bin/env python
import sys
import imaplib
import getpass
import email
import datetime
import socket
import os
import sys
def process_mailbox(M):
betweenDates = '(SINCE 01-Mar-2014 BEFORE 30-Apr-2014)'
M.select('INBOX')
rv, data = M.search(None, "ALL", betweenDates)
# rv, data = M.search(None, "UNSEEN",betweenDates)
if rv != 'OK':
print "No messages found!"
return
for num in data[0].split():
rv, data = M.fetch(num, '(RFC822)')
if rv != 'OK':
print "ERROR getting message", num
return
emailBody = data[0][1]
mail = email.message_from_string(emailBody)
#print 'Raw Date:', mail['Date'],
date_tuple = email.utils.parsedate_tz(mail['Date'])
if date_tuple:
local_date = datetime.datetime.fromtimestamp( email.utils.mktime_tz(date_tuple))
#print "Local Date:", local_date.strftime("%a, %d %b %Y %H:%M:%S")
for part in mail.walk():
if part.get_content_maintype() == 'multipart':
# print part.as_string()
continue
if part.get('Content-Disposition') is None:
# print part.as_string()
continue
fileName = part.get_filename()
#print fileName
if bool(fileName):
filePath = os.path.join(detach_dir, 'attachments', fileName)
if not os.path.isfile(filePath) :
#if 1==1:
print fileName,
print " ", local_date.strftime(" %d %b %Y ")
fp = open(filePath, 'wb')
if fp != None:
fp.write(part.get_payload(decode=True))
fp.close()
detach_dir = '.'
if 'attachments' not in os.listdir(detach_dir):
os.mkdir('attachments')
M = imaplib.IMAP4_SSL('imap.gmail.com')
try:
M.login('set_your_mail_addres_here@gmail.com', getpass.getpass())
rv, mailboxes = M.list()
if rv == 'OK':
print M.list()
print "Processing mailbox...\n"
process_mailbox(M) # ... do something with emails, see below ...
M.close()
M.logout()
#except imaplib.IMAP4.error:
except socket.error, e:
print e
print "LOGIN FAILED!!! "
# ... exit
M.close()
M.logout()
#or deal with failure...
Скрипт пишет все аттачменты в ./attachments
Работает не только с gmail.com, правда gmail уже требует oauth2. Для того что бы скрипт не завалил логин нужно отключить oauth в gmail.com.