get email subject working
This commit is contained in:
parent
ee4d356506
commit
bf60b4b452
1 changed files with 23 additions and 9 deletions
|
|
@ -1,11 +1,7 @@
|
|||
# %%
|
||||
|
||||
import base64
|
||||
import email
|
||||
import imaplib
|
||||
|
||||
# %%
|
||||
import json
|
||||
from email.header import decode_header
|
||||
from imaplib import IMAP4, IMAP4_SSL
|
||||
from pathlib import Path
|
||||
|
||||
|
|
@ -26,8 +22,26 @@ imap_port = 143
|
|||
imap_ssl_port = 993
|
||||
|
||||
|
||||
# with IMAP4("domain.org") as M:
|
||||
# M.noop()
|
||||
with IMAP4_SSL(host=host) as imap_server:
|
||||
imap_server.login(username, password)
|
||||
imap_server.select("INBOX")
|
||||
|
||||
with IMAP4_SSL(host=host) as M:
|
||||
M.noop()
|
||||
# Search for all emails in the folder
|
||||
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)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue