SMTP (Simple Mail Transfer Protocol) 是一种用于发送电子邮件的互联网标准协议。Python通过smtplib
模块提供了SMTP协议的支持,可以方便地发送电子邮件。
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# 配置信息
smtp_server = "smtp.example.com" # SMTP服务器地址
smtp_port = 587 # 端口号,通常是587(TLS)或465(SSL)
sender_email = "your_email@example.com"
sender_password = "your_password"
receiver_email = "recipient@example.com"
# 创建邮件内容
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = "Python SMTP 测试邮件"
# 邮件正文
body = """
这是一封通过Python SMTP发送的测试邮件。
"""
message.attach(MIMEText(body, "plain"))
try:
# 创建SMTP连接
with smtplib.SMTP(smtp_server, smtp_port) as server:
server.starttls() # 启用TLS加密
server.login(sender_email, sender_password)
server.sendmail(sender_email, receiver_email, message.as_string())
print("邮件发送成功!")
except Exception as e:
print(f"邮件发送失败: {e}")
html = """\
<html>
<body>
<p>这是一封<strong>HTML格式</strong>的邮件</p>
</body>
</html>
"""
message.attach(MIMEText(html, "html"))
from email.mime.base import MIMEBase
from email import encoders
filename = "example.pdf" # 附件文件路径
with open(filename, "rb") as attachment:
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)
recipients = ["recipient1@example.com", "recipient2@example.com"]
message["To"] = ", ".join(recipients)
通过Python的SMTP功能,开发者可以轻松实现各种邮件发送需求,从简单的通知到复杂的邮件营销系统。
没有搜到相关的文章