Fetch emails
*****This code Works only for the text email formats.*****unknown
python
2 years ago
2.5 kB
4
Indexable
import imaplib import email from email.header import decode_header from User_credentials import * def fetch_and_print_emails(): # Email account credentials email_address = sender_Email_Id password = sender_AppKey try: # Connect to the IMAP server mail = imaplib.IMAP4_SSL("imap.gmail.com") mail.login(email_address, password) # Select the mailbox (inbox in this case) mail.select("inbox") # Search for all emails status, messages = mail.search(None, "ALL") mail_id = messages[0].split() mail_ids = mail_id[-5:] for mail_id in reversed(mail_ids): try: _, msg_data = mail.fetch(mail_id, "(RFC822)") raw_email = msg_data[0][1] msg = email.message_from_bytes(raw_email) # Get email details subject, encoding = decode_header(msg["Subject"])[0] if isinstance(subject, bytes): subject = subject.decode(encoding or "utf-8") print(f"Subject: {subject}") print(f"From: {msg['From']}") # Print the email body if msg.is_multipart(): for part in msg.walk(): content_type = part.get_content_type() content_disposition = str(part.get("Content-Disposition")) if "attachment" not in content_disposition: if content_type == "text/plain": body = part.get_payload(decode=True) if body is not None: print("Body (text):", body.decode("utf-8")) elif content_type == "text/html": body = part.get_payload(decode=True) if body is not None: print("Body (HTML):", body.decode("utf-8")) print("=" * 40) # Separator between emails except Exception as e: print(f"Error processing email ID {mail_id}: {e}") except Exception as e: print(f"An error occurred: {e}") finally: # Logout and close the connection if mail: mail.logout() # Call the function to fetch and print emails fetch_and_print_emails()
Editor is loading...