📧 使用Python的smtplib和email模块实现邮件收发功能
在Python中,smtplib
和email
模块是处理电子邮件的强大工具。本文将通过多个案例代码,详细介绍如何使用这两个模块来发送和接收电子邮件。🚀
🔨 环境准备
在开始之前,请确保你的Python环境中已经安装了smtplib
和email
模块。这两个模块是Python标准库的一部分,通常不需要额外安装。
📬 发送邮件
1. 简单文本邮件
import smtplib
from email.mime.text import MIMEText# 设置发件人和收件人信息
sender_email = "your_email@example.com"
receiver_email = "recipient_email@example.com"# 设置邮件内容
message = MIMEText("Hello, this is a simple email message.")
message["Subject"] = "Simple Email Test"
message["From"] = sender_email
message["To"] = receiver_email# 设置SMTP服务器并发送邮件
with smtplib.SMTP("smtp.example.com", 587) as server:server.starttls() # 启用加密server.login(sender_email, "your_password") # 登录邮箱server.sendmail(sender_email, receiver_email, message.as_string()) # 发送邮件
2. 带附件的邮件
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication# 创建一个多部分邮件
msg = MIMEMultipart()
msg["From"] = sender_email
msg["To"] = receiver_email
msg["Subject"] = "Email with Attachment"# 添加文本内容
body = "This is the email body with an attachment."
text = MIMEText(body, "plain")
msg.attach(text)# 添加附件
filename = "example.jpg"
attachment = open(filename, "rb")
part = MIMEApplication(attachment.read(), _subtype="jpg")
part.add_header("Content-Disposition",f"attachment; filename= {filename}",
)
msg.attach(part)# 发送邮件
with smtplib.SMTP("smtp.example.com", 587) as server:server.starttls()server.login(sender_email, "your_password")server.sendmail(sender_email, receiver_email, msg.as_string())
📭 接收邮件
1. 使用IMAP协议接收邮件
import imaplib# 设置邮箱信息
username = "your_email@example.com"
password = "your_password"
imap_url = "imap.example.com"# 连接IMAP服务器
mail = imaplib.IMAP4_SSL(imap_url)
mail.login(username, password)# 选择邮箱中的收件箱
mail.select("inbox")# 搜索所有邮件
status, messages = mail.search(None, 'ALL')
messages = messages[0].split()# 读取并打印每封邮件的内容
for num in messages:status, data = mail.fetch(num, '(RFC822)')raw_email = data[0][1]print("Email Content: ")print(raw_email.decode('utf-8'))
⚠️ 注意事项
- 请确保替换代码中的
your_email@example.com
、recipient_email@example.com
、smtp.example.com
、your_password
和imap.example.com
为你自己的邮箱信息和服务器地址。 - 发送邮件时,出于安全考虑,不要在代码中明文存储你的邮箱密码。可以使用环境变量或其他安全方式来管理敏感信息。
- 接收邮件时,确保你的邮箱服务器支持IMAP协议,并且正确设置了IMAP服务器地址和端口。
通过上述案例代码,你应该能够使用Python的smtplib
和email
模块来实现基本的邮件收发功能。🎉 记得在实际应用中,根据需要调整和完善代码。