Feb-21-2024, 05:48 PM
Hi Team,
I am trying to write a code which would download the TLS Report messages and then extract messages, unzip it and store it in file. Since I am not pro I happen to write few lines but the attachments are not getting downloaded.
The code then says it would search for the messages when matching content found in BODY but those are throwing exception.
Can someone please help me here?
Blason R
I am trying to write a code which would download the TLS Report messages and then extract messages, unzip it and store it in file. Since I am not pro I happen to write few lines but the attachments are not getting downloaded.
The code then says it would search for the messages when matching content found in BODY but those are throwing exception.
Can someone please help me here?
import imaplib import email import json import os # IMAP server credentials IMAP_SERVER = 'imap.xxxx.net' EMAIL_ADDRESS = '[email protected]' PASSWORD = 'XXXXXXX' # Directory to save JSON files SAVE_DIR = '/tmp/tls' def connect_to_imap_server(): # Connect to the IMAP server mail = imaplib.IMAP4_SSL(IMAP_SERVER) mail.login(EMAIL_ADDRESS, PASSWORD) return mail def download_tls_rpt_reports(): # Create directory if it doesn't exist if not os.path.exists(SAVE_DIR): os.makedirs(SAVE_DIR) mail = connect_to_imap_server() mail.select("inbox") # Search for emails containing TLS-RPT reports result, data = mail.search(None, 'SUBJECT', 'Report') for num in data[0].split(): result, data = mail.fetch(num, '(RFC822)') raw_email = data[0][1] msg = email.message_from_bytes(raw_email) # Extract JSON attachment (if any) for part in msg.walk(): if part.get_content_type() == "application/json": filename = part.get_filename() if filename: with open(os.path.join(SAVE_DIR, filename), 'wb') as f: f.write(part.get_payload(decode=True)) print(f"Saved TLS-RPT report: {filename}") mail.close() mail.logout() if __name__ == "__main__": download_tls_rpt_reports()TIA
Blason R