Python: download email using IMAP

import imaplib
import email
from email.header import decode_header

# IMAP credentials
imap_host = 'imap_server'
email_user = 'user_name'
email_pass = 'password'

# Connect and log in
mail = imaplib.IMAP4_SSL(imap_host)
mail.login(email_user, email_pass)

# Select mailbox (e.g., inbox)
mail.select('inbox')

# Search emails (you can refine the query)
status, messages = mail.search(None, '(HEADER Subject "RSDA Data Error")')
email_ids = messages[0].split()

# Fetch the latest email
latest_email_id = email_ids[-1]
status, msg_data = mail.fetch(latest_email_id, '(RFC822)')

# Parse email content
raw_email = msg_data[0][1]
msg = email.message_from_bytes(raw_email)

# Decode subject
subject, encoding = decode_header(msg['Subject'])[0]
if isinstance(subject, bytes):
    subject = subject.decode(encoding if encoding else 'utf-8')

# Extract body
body = ""
if msg.is_multipart():
    for part in msg.walk():
        if part.get_content_type() == 'text/plain' and part.get_content_disposition() is None:
            body = part.get_payload(decode=True).decode()
            break
else:
    body = msg.get_payload(decode=True).decode()

# Write to file
with open("email_output.txt", "w", encoding="utf-8") as f:
    f.write(f"Subject: {subject}\n\n")
    f.write(f"Body:\n{body}")

# Logout
mail.logout()
创建时间:8/6/2025 11:03:05 AM 修改时间:8/6/2025 11:03:47 AM