经测试可用的发送邮件代码:python
import smtplib
from email.mime.text import MIMEText
# 第三方 SMTP 服务
mail_host = "smtp.163.com" # SMTP服务器
mail_user = "username" # 用户名
mail_pass = "passwd" # 密码(这里的密码不是登陆邮箱密码,而是受权码)
sender = 'sender_mail@163.com' # 发件人邮箱
receivers = ['receive_mail@qq.com'] # 接收人邮箱
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(),端口号为465ui
2.报错:535, b'Error: authentication failed'编码
解决:多是因为用户名不正确,所以代码中的用户名应该填写为邮箱地址@前面部分 ,或是在邮箱设置的账户昵称,以下图昵称Morning和马赛克部分,均可做为用户名spa
3.SMTP服务器可根据发送的邮箱作相应的选择,如代码中使用163邮箱则设为mail_host = "smtp.163.com" orm
能够改为"smtp.126.com"、"smtp.qq.com"等等blog
4.代码中的密码mail_pass为受权码,并不是邮箱密码,受权码用于登陆第三方邮件客户端的专用密码utf-8
QQ邮箱可经过设置→账户→生成受权码;网易邮箱126/163可经过设置→客户端受权密码ssl