Python can be used to read emails by using the following steps:
imaplib
, email
, and datetime
email
library to extract relevant information such as the sender, subject, body, and attachmentsHere is an example of how to read and display the latest email from the Inbox folder:
import imaplib import email import datetime # Set email login credentials email_user = "your_email@example.com" email_pass = "your_password" # Set connection variables mail = imaplib.IMAP4_SSL("imap.gmail.com") mail.login(email_user, email_pass) mail.select("Inbox") # Select Inbox folder # Search for the latest email date = (datetime.date.today() - datetime.timedelta(1)).strftime("%d-%b-%Y") result, data = mail.search(None, f'(SENTSINCE {date})') # Retrieve the latest email data latest_email_id = data[0].split()[-1] result, data = mail.fetch(latest_email_id, "(RFC822)") # Parse the email data raw_email = data[0][1] email_message = email.message_from_bytes(raw_email) email_subject = email_message["Subject"] email_from = email_message["From"] email_body = email_message.get_payload() # Display email information print(f"From: {email_from}") print(f"Subject: {email_subject}") print(f"Body:\n{email_body}") # Close the email connection mail.close() mail.logout()
Note: This example assumes that the emails are stored on a Gmail server and that the user has enabled IMAP access for their account. The code may need to be modified for other email providers or configurations.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2021-08-25 11:00:00 +0000
Seen: 9 times
Last updated: Oct 23 '21