get email subject working

This commit is contained in:
Daniel 2023-12-04 12:40:57 +01:00
parent ee4d356506
commit bf60b4b452

View file

@ -1,11 +1,7 @@
# %% # %%
import base64
import email import email
import imaplib
# %%
import json import json
from email.header import decode_header
from imaplib import IMAP4, IMAP4_SSL from imaplib import IMAP4, IMAP4_SSL
from pathlib import Path from pathlib import Path
@ -26,8 +22,26 @@ imap_port = 143
imap_ssl_port = 993 imap_ssl_port = 993
# with IMAP4("domain.org") as M: with IMAP4_SSL(host=host) as imap_server:
# M.noop() imap_server.login(username, password)
imap_server.select("INBOX")
with IMAP4_SSL(host=host) as M: # Search for all emails in the folder
M.noop() status, email_ids = imap_server.search(None, "ALL")
email_ids = email_ids[0].split()
# Fetch email details using the retrieved IDs
for email_id in email_ids:
result, data = imap_server.fetch(email_id, "(RFC822)")
raw_email = data[0][1] # Raw content of the email
email_message = email.message_from_bytes(raw_email)
# Extract the subject
subject_encoded = email_message.get("Subject")
decoded_subject = decode_header(subject_encoded)[0][0]
if isinstance(decoded_subject, bytes):
decoded_subject = decoded_subject.decode()
# Print or use the subject as needed
print("Subject:", decoded_subject)