python email模块使用方法
在Python中,可以使用email模块来处理电子邮件。以下是一些email模块的常用方法和示例:
- 创建一个简单的文本邮件:
import smtplib
from email.mime.text import MIMEText
msg = MIMEText("This is a test email.")
msg['Subject'] = "Test Email"
msg['From'] = "sender@example.com"
msg['To'] = "recipient@example.com"
# 发送邮件
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()
- 创建一个带附件的邮件:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
msg = MIMEMultipart()
msg['Subject'] = "Test Email with Attachment"
msg['From'] = "sender@example.com"
msg['To'] = "recipient@example.com"
# 添加文本内容
text = MIMEText("This is a test email with attachment.")
msg.attach(text)
# 添加图片附件
with open("image.jpg", "rb") as f:
image = MIMEImage(f.read())
image.add_header('Content-Disposition', 'attachment', filename="image.jpg")
msg.attach(image)
# 发送邮件
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()
- 解析收到的邮件:
import imaplib
import email
# 连接到IMAP服务器
imap_server = imaplib.IMAP4('imap.example.com')
imap_server.login('username', 'password')
imap_server.select('INBOX')
# 搜索邮件
status, email_ids = imap_server.search(None, 'ALL')
# 获取邮件内容
for email_id in email_ids[0].split():
status, email_data = imap_server.fetch(email_id, '(RFC822)')
raw_email = email_data[0][1]
email_message = email.message_from_bytes(raw_email)
print(email_message['From'])
print(email_message['Subject'])
print(email_message.get_payload())
# 关闭IMAP连接
imap_server.close()
imap_server.logout()
这些示例只是email模块的一部分功能。要了解更多关于email模块的信息,可以查阅官方文档:https://docs.python.org/3/library/email.htm
原文地址: https://www.cveoy.top/t/topic/hy8K 著作权归作者所有。请勿转载和采集!