Created
February 28, 2024 09:35
-
-
Save iamshreeram/3f15f4fc0345658959c3430b8293b7e6 to your computer and use it in GitHub Desktop.
read-email from gmail
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import imaplib | |
import email | |
# Gmail IMAP server details | |
IMAP_SERVER = "imap.gmail.com" | |
IMAP_PORT = 993 | |
# Gmail account credentials | |
EMAIL = "[email protected]" | |
PASSWORD = "your_password" | |
# Connect to the Gmail IMAP server | |
mail = imaplib.IMAP4_SSL(IMAP_SERVER, IMAP_PORT) | |
# Login to the Gmail account | |
mail.login(EMAIL, PASSWORD) | |
# Select the mailbox to read emails from (e.g., "INBOX") | |
mail.select("INBOX") | |
# Search for emails based on specific criteria | |
status, data = mail.search(None, "ALL") # Retrieve all emails | |
# Get the list of email IDs | |
email_ids = data[0].split() | |
email_count = len(email_ids) | |
# Iterate over email IDs in reverse order (from newest to oldest) | |
for i in range(email_count - 1, -1, -1): | |
# Fetch the email for the given ID | |
status, data = mail.fetch(email_ids[i], "(RFC822)") | |
# Parse the email data | |
raw_email = data[0][1] | |
msg = email.message_from_bytes(raw_email) | |
# Extract email details (e.g., sender, subject, body) | |
sender = msg["From"] | |
subject = msg["Subject"] | |
body = "" | |
# Check if the email has multiple parts (e.g., plain text and HTML) | |
if msg.is_multipart(): | |
for part in msg.get_payload(): | |
if part.get_content_type() == "text/plain": | |
body = part.get_payload(decode=True).decode("UTF-8") | |
break | |
else: | |
body = msg.get_payload(decode=True).decode("UTF-8") | |
# Print email details | |
print("Sender:", sender) | |
print("Subject:", subject) | |
print("Body:", body) | |
print("---") | |
# Logout from the Gmail account | |
mail.logout() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment