在 Python 中,可以使用内置的 smtplib
库来发送邮件。已知邮箱和密码时,以下是实现自动发送邮件的完整步骤:
代码实现
示例代码:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def send_email(sender_email, sender_password, recipient_email, subject, body):
try:
# SMTP服务器配置 (以Gmail为例,可替换为其他服务)
smtp_server = "smtp.gmail.com"
smtp_port = 587 # 使用 TLS 的端口
# 创建邮件对象
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = recipient_email
message["Subject"] = subject
# 添加邮件正文
message.attach(MIMEText(body, "plain")) # 纯文本邮件正文
# 连接到SMTP服务器并登录
with smtplib.SMTP(smtp_server, smtp_port) as server:
server.starttls() # 启用 TLS 加密
server.login(sender_email, sender_password) # 登录邮箱
server.sendmail(sender_email, recipient_email, message.as_string()) # 发送邮件
print("Email sent successfully!")
except Exception as e:
print(f"Failed to send email: {
e}")
# 示例调用
if __name__ == "__main__":
sender_email = "your_email@example.com"
sender_password = "your_password"
recipient_email = "recipient@example.com"
subject = "Test Email"
body = "This is a test email sent from Python."
send_email(sender_email, sender_password, recipient_email, subject, body)
配置说明
1. 替换邮箱服务配置
- Gmail 配置:
- SMTP 服务器:
smtp.gmail.com
- 端口:587(TLS)或 465(SSL)
- SMTP 服务器:
- Outlook 配置:
- SMTP 服务器:
smtp.office365.com
- 端口:587
- SMTP 服务器:
- QQ 邮箱:
- SMTP 服务器:
smtp.qq.com
- 端口:465(SSL)
- SMTP 服务器:
根据你的邮箱服务提供商,替换 smtp_server
和 smtp_port
。
2. 邮箱设置
- Gmail:
- 确保启用了“允许不太安全的应用”或使用应用专用密码。
- QQ 邮箱:
- 需要开启 SMTP 服务,并获取授权码(授权码代替密码)。
- Outlook:
- 默认支持 SMTP,只需邮箱密码。
重要注意事项
-
安全性
- 不要将明文密码保存在代码中。
- 使用环境变量或配置文件存储敏感信息。
示例:使用环境变量
import os sender_password = os.getenv("EMAIL_PASSWORD"