Created
June 8, 2022 08:55
-
-
Save greyblue9/bbfdc1adb2f03c962c07347f8db314eb to your computer and use it in GitHub Desktop.
Retrieve messages from gmail using imaplib
This file contains 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
from dotenv import load_dotenv | |
from email import message_from_bytes | |
from imaplib import IMAP4_SSL | |
from itertools import islice | |
from os import getenv | |
from pathlib import Path | |
load_dotenv() | |
username = getenv("GMAIL_USERNAME") | |
password = getenv("GMAIL_APP_PASS") | |
message_limit = 5 | |
# connect to IMAP server | |
with IMAP4_SSL("imap.gmail.com") as conn: | |
if not username or not password: | |
raise Exception( | |
f"Missing credentials in {Path.cwd()/'.env'!s}. " | |
"Need GMAIL_USERNAME, GMAIL_APP_PASS" | |
) | |
conn.login(username, password) | |
conn.select() | |
# search for all messages | |
result, data = conn.uid("search", None, "ALL") | |
if result != "OK": | |
raise Exception(f"Error searching: {result}") | |
# process the first <message_limit> message numbers | |
for num in islice(data[0].split(), 0, message_limit): | |
print(f"Fetching message headers: {num=}") | |
# fetch message headers | |
result, data = conn.uid("fetch", num, "(RFC822)") | |
if result != "OK": | |
continue | |
# decode message headers | |
message = message_from_bytes(data[0][1]) | |
# fetch message body, attachments, etc. | |
body, *attachments = message.get_payload() | |
print("From:", message["From"]) | |
print("To:", message["To"]) | |
print("Date:", message["Date"]) | |
print("Subject:", message["Subject"]) | |
print("Content:", body) | |
conn.logout() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment