Feb-25-2024, 06:11 PM
I modified your code a little, you seem to have repeated variable names which may have caused confusion.
I wrote Report in the email Subject field.
This still doesn't mark mails as SEEN, also it overwrites a file with the same name without hesitation.
Works for me!
I wrote Report in the email Subject field.
This still doesn't mark mails as SEEN, also it overwrites a file with the same name without hesitation.
Works for me!
import imaplib import email import os # IMAP server credentials savepath = '/home/pedro/myPython/email_stuff/' imap_server = "imap.yourmail.com" sender_of_interest = '[email protected]' email_address = '[email protected]' password = 'topsecret' label = 'INBOX' subject = 'Report' # make a folder to hold the files if 'email_attachments' not in os.listdir(savepath): os.mkdir(savepath + 'email_attachments') def connect_to_imap_server(s, e, p): # Connect to the IMAP server mail = imaplib.IMAP4_SSL(s) mail.login(e, p) return mail def download_tls_rpt_reports(): M = connect_to_imap_server(imap_server, email_address, password ) M.select(label) # Search for emails containing TLS-RPT reports #typ, data = imapSession.search(None, 'UNSEEN', f'FROM {sender_of_interest}') result, data = M.search(None, 'UNSEEN', f'SUBJECT {subject}') for num in data[0].split(): status, messageParts = M.fetch(num, '(RFC822)') emailBody = messageParts[0][1] raw_email_string = emailBody.decode('utf-8') msg = email.message_from_string(raw_email_string) # Extract JSON attachment (if any) for part in msg.walk(): if part.get_content_type() == "application/json": filename = part.get_filename() if filename: filePath = os.path.join(savepath, 'email_attachments', filename) with open(filePath, 'wb') as f: f.write(part.get_payload(decode=True)) print(f"Saved TLS-RPT report: {filePath}") M.close() M.logout() if __name__ == "__main__": download_tls_rpt_reports()Output:
Output:download_tls_rpt_reports()
Saved TLS-RPT report: /home/pedro/myPython/email_stuff/email_attachments/example2.json