经测试可用的发送邮件代码:
import smtplib
from email.mime.text import MIMEText
# 第三方 SMTP 服务
mail_host = "smtp.163.com" # SMTP服务器
mail_user = "username" # 用户名
mail_pass = "passwd" # 密码
sender = '[email protected]' # 发件人邮箱
receivers = ['[email protected]'] # 接收人邮箱
content = 'Python Send Mail !'
title = 'Python SMTP Mail Test' # 邮件主题
message = MIMEText(content, 'plain', 'utf-8') # 内容, 格式, 编码
message['From'] = "{}".format(sender)
message['To'] = ",".join(receivers)
message['Subject'] = title
try:
smtpObj = smtplib.SMTP_SSL(mail_host, 465) # 启用SSL发信, 端口一般是465
smtpObj.login(mail_user, mail_pass) # 登录验证
smtpObj.sendmail(sender, receivers, message.as_string()) # 发送
print("mail has been send successfully.")
except smtplib.SMTPException as e:
print(e)
问题解决与注意点:
1.报错:Error: A secure connection is requiered(such as ssl)
解决:因为邮箱SSL验证的问题,因此把smtplib.SMTP()改成smtplib.SMTP_SSL(),端口号为465
2.报错:535, b'Error: authentication failed'
解决:可能是由于用户名不正确,因此代码中的用户名应该填写为邮箱地址@前面部分 ,或是在邮箱设置的帐户昵称,如下图昵称Morning和马赛克部分,都可作为用户名
3.SMTP服务器可根据发送的邮箱做相应的选择,如代码中使用163邮箱则设为mail_host = "smtp.163.com"
可以改成"smtp.126.com"、"smtp.qq.com"等等
4.代码中的密码mail_pass为授权码,并非邮箱密码,授权码用于登录第三方邮件客户端的专用密码
QQ邮箱可通过设置→帐户→生成授权码;网易邮箱126/163可通过设置→客户端授权密码