I am trying to download all the attachments from the INBOX.
After 10 to 20 downloaded files, the program throws an error.
, line 62, in
get_attachments(raw,email_id)
,line 31, in get_attachments
fileName = '{} '.format(email_id)+part.get_filename()
TypeError: must be str, not NoneType
Plus, I'm trying to change the code to download received files within 24 hours from INBOX and save in my download folder.
import imaplib, email, os
user = "***"
password = "***"
imap_url = "smtp.outlook.com"
attachment_dir = "/GGG/"
# sets up the auth
def auth(user,password,imap_url):
con = imaplib.IMAP4_SSL(imap_url)
con.login(user,password)
return con
# extracts the body from the email
def get_body(msg):
if msg.is_multipart():
return get_body(msg.get_payload(0))
else:
return msg.get_payload(None,True)
# allows you to download attachments
def get_attachments(msg,email_id):
for part in msg.walk():
if part.get_content_maintype()=='multipart':
continue
if part.get('Content-Disposition') is None:
continue
fileName = '{} '.format(email_id)+part.get_filename()
if bool(fileName):
filePath = os.path.join(attachment_dir, fileName)
with open(filePath,'wb') as f:
f.write(part.get_payload(decode=True))
#search for a particular email
def search(key,value,con):
result, data = con.search(None,key,'"{}"'.format(value))
return data
#extracts emails from byte array
def get_emails(result_bytes):
msgs = []
for num in result_bytes[0].split():
typ, data = con.fetch(num, '(RFC822)')
msgs.append(data)
return msgs
con = auth(user,password,imap_url)
#All I added is below here
#########################################################
#A method of obtaining inbox size
inbox_size = int(con.select('INBOX')[1][0])
#Here I used a for loop to go through all email ids
for email_id in range(1,inbox_size+1):
result, data = con.fetch(str(email_id).encode(),'(RFC822)')
raw = email.message_from_bytes(data[0][1])
get_attachments(raw,email_id)