1. 发送纯文本邮件
import smtplib
from email.mime.text import MIMEText
# 邮件配置
smtp_server = 'smtp.example.com' # 替换为您的SMTP服务器
smtp_port = 587 # 通常587用于TLS,465用于SSL
sender_email = 'your_email@example.com'
password = 'your_password_or_app_password' # 使用授权码而非登录密码
receiver_email = 'recipient@example.com'
# 创建邮件内容
subject = 'Python邮件测试'
body = '这是一封来自Python的测试邮件。'
# 创建MIMEText对象
message = MIMEText(body, 'plain', 'utf-8')
message['From'] = sender_email
message['To'] = receiver_email
message['Subject'] = subject
# 发送邮件
try:
with smtplib.SMTP(smtp_server, smtp_port) as server:
server.starttls() # 启用TLS加密
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message.as_string())
print("邮件发送成功!")
except Exception as e:
print(f"邮件发送失败: {e}")
发表评论