Feb-25-2024, 09:38 AM
This works for me, downloads a small json file example3.json but it should collect any file, I think!
Probably better to only get files from people you know, or you might pick up some nasty stuff!
Strangely, when I do this step by step, I have to use:
But, within myApp() this works fine! Can't figure that out!
This does not mark the emails as SEEN, but you can add that if you wish.
For testing, I kept this mail as unread.
Probably better to only get files from people you know, or you might pick up some nasty stuff!
Strangely, when I do this step by step, I have to use:
Quote:typ, messageParts = imapSession.fetch(msgId[0], '(RFC822)') # msgId is a list
But, within myApp() this works fine! Can't figure that out!
Quote:typ, messageParts = imapSession.fetch(msgId, '(RFC822)')
import email import imaplib import os savepath = '/home/pedro/myPython/email_stuff/' imap_server = "imap.yourmail.com" sender_of_interest = '[email protected]' email_address = '[email protected]' password = 'topsecret' label = 'INBOX' # make a folder to hold the files if 'email_attachments' not in os.listdir(savepath): os.mkdir(savepath + 'email_attachments') def myApp(): try: imapSession = imaplib.IMAP4_SSL(imap_server) typ, accountDetails = imapSession.login(email_address, password) imapSession.select(label) typ, data = imapSession.search(None, 'UNSEEN', f'FROM {sender_of_interest}') print(typ, data) print('Search...') for msgId in data[0].split(): # msgId is a list I need msgId[0] when I do this step by step typ, messageParts = imapSession.fetch(msgId, '(RFC822)') emailBody = messageParts[0][1] raw_email_string = emailBody.decode('utf-8') mail = email.message_from_string(raw_email_string) print('got the whole email body as a string...') for part in mail.walk(): if part.get_content_maintype() == 'multipart': print(part.as_string()) continue if part.get('Content-Disposition') is None: print(f'This part has Content-Disposition: {part.as_string()}') continue fileName = part.get_filename() print(f'file name {fileName} being processed ...') if bool(fileName): filePath = os.path.join(savepath, 'email_attachments', fileName) # don't overwrite if file exists can change this behaviour if wanted if not os.path.isfile(filePath): print(f'the file is {fileName}') fp = open(filePath, 'wb') fp.write(part.get_payload(decode=True)) fp.close() print('fp closed ...') imapSession.close() imapSession.logout() except: print('Not able to download all attachments.')Hope it works for you!
This does not mark the emails as SEEN, but you can add that if you wish.
For testing, I kept this mail as unread.