SMTP(Simple Mail Transfer Protocol)是用于发送邮件的标准协议。Python 中的 smtplib 模块提供了发送邮件的功能,可以通过 SMTP 服务器发送电子邮件。
下面通过一个简单的案例来说明如何使用 Python 的 smtplib 模块发送邮件:
```python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
# 设置发件人和收件人
sender_email = "your_email@gmail.com"
receiver_email = "recipient_email@gmail.com"
password = "your_password"
# 创建邮件内容
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = "Test Email from Python"
body = "This is a test email sent from Python."
message.attach(MIMEText(body, "plain"))
# 添加附件
filename = "example.txt"
attachment = open(filename, "rb")
part = MIMEBase("application", "octet-stream")
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header("Content-Disposition", f"attachment; filename= {filename}")
message.attach(part)
# 连接到 SMTP 服务器并发送邮件
with smtplib.SMTP('smtp.gmail.com', 587) as server:
server.starttls()
server.login(sender_email, password)
text = message.as_string()
server.sendmail(sender_email, receiver_email, text)
print("Email sent successfully!")
```
在这个案例中,我们首先设置了发件人、收件人和密码。然后创建了一个包含邮件主题、正文和附件的邮件内容。接着,通过 `smtplib.SMTP` 连接到 SMTP 服务器(这里以 Gmail 为例),使用 `starttls()` 开启安全连接,然后调用 `login()` 方法登录发件人邮箱。最后,将邮件内容转换为字符串并使用 `sendmail()` 方法发送邮件。
以上是一个简单的示例,展示了如何使用 Python 的 smtplib 模块发送带有附件的邮件。实际应用中,可以根据需求定制更复杂的邮件内容和逻辑,并处理可能出现的异常情况以确保邮件发送的稳定性。