使用 Python 发送电子邮件

发送邮件

from smtplib import SMTP
from email.mime.text import MIMEText
from email.header import Header

message = MIMEText("Put email content here", "plain", "utf-8")
message["From"] = "foo@gmail.com"
message["To"] = "bar@gmail.com"
message["Subject"] = Header("Put email subject here", "utf-8")

with SMTP("smtp.gmail.com", 587) as server:
    server.starttls()
    server.login("foo@gmail.com", "your-app-password")
    server.sendmail("foo@gmail.com", "bar@gmail.com", message.as_string())

接收邮件

from imaplib import IMAP4_SSL
from email import message_from_bytes
from email.header import decode_header

def decode_email_header(header):
    decoded_header = decode_header(header)
    return ''.join([str(t[0], t[1] or 'utf-8') if isinstance(t[0], bytes) else t[0] for t in decoded_header])

mail = IMAP4_SSL("imap.gmail.com", 993)
mail.login("foo@gmail.com", "your-app-password")
mail.select('INBOX')

_, id_list = mail.search(None, 'ALL')
latest_id = id_list[0].split()[-1]
_, msg_data = mail.fetch(latest_id, '(RFC822)')
body = msg_data[0][1]
message = message_from_bytes(body)

print(f"From: {message['from']}")
print(f"Subject: {decode_email_header(message['subject'])}")
print(f"Date: {message['date']}")

if message.is_multipart():
    for part in message.walk():
        if part.get_content_type() == "text/plain":
            body = part.get_payload(decode=True).decode()
            print("Content:", body)
            break
else:
    body = message.get_payload(decode=True).decode()
    print("Content:", body)

mail.close()
mail.logout()

参见:Undefined443/simple-email-client | GitHub

posted @ 2024-12-16 00:34  Undefined443  阅读(25)  评论(0)    收藏  举报