import email
import getpass, imaplib
import os
import sys
import datetime

#get only emails which are newer than 14 days
date = (datetime.date.today() - datetime.timedelta(14)).strftime("%d-%b-%Y")

detach_dir = '.'
#if directory attachments does not exist, create it
if 'attachments' not in os.listdir(detach_dir):
    os.mkdir('attachments')
#specify your username and password
username='USERNAMEHERE'
passwd = 'PASSWORDHERE'
#initiate a Yahoo mail session
imapSession = imaplib.IMAP4_SSL('imap.mail.yahoo.com')

typ, accountDetails = imapSession.login(username, passwd)
#select only unread messages
imapSession.select(readonly=1)
#select only messaged that are newer than 14 days
typ, data = imapSession.search(None, '(UNSEEN SENTSINCE {date})'.format(date=date))

# Iterating over all emails
for msgId in data[0].split():
   
   	print msgId
        typ, messageParts = imapSession.fetch(msgId, '(RFC822)')
        if typ != 'OK':
            print 'Error fetching mail.'
            raise

        emailBody = messageParts[0][1]
        mail = email.message_from_string(emailBody)
	
        for part in mail.walk():
            print part.as_string()
            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()
	   #if there is an attachment
            if bool(fileName):
            	#save it in the attachments directory
                filePath = os.path.join(detach_dir, 'attachments', fileName)
                if not os.path.isfile(filePath) :
                    print fileName
                    fp = open(filePath, 'wb')
                    fp.write(part.get_payload(decode=True))
                    fp.close()
#close the yahoo mail session and log out  
imapSession.close()
imapSession.logout()

