使用python3发送网易邮箱邮件
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| import smtplib from email.mime.text import MIMEText from email.header import Header
def send_email(mail_host, from_account, from_passwd, to_account, subject, content): mail = smtplib.SMTP() mail.connect(mail_host) mail.login(from_account, from_passwd)
# 发送邮件 message = MIMEText(content, 'plain', 'utf-8') message['From'] = from_account message['To'] = to_account message['Subject'] = Header(subject, 'utf-8') mail.sendmail(from_account, to_account, message.as_string())
|
菜鸟教程上有一种写法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| #!/usr/bin/python3 import smtplib from email.mime.text import MIMEText from email.header import Header # 第三方 SMTP 服务 mail_host="smtp.XXX.com" #设置服务器 mail_user="XXXX" #用户名 mail_pass="XXXXXX" #口令 sender = 'from@runoob.com' receivers = ['429240967@qq.com'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱 message = MIMEText('Python 邮件发送测试...', 'plain', 'utf-8') message['From'] = Header("菜鸟教程", 'utf-8') message['To'] = Header("测试", 'utf-8') subject = 'Python SMTP 邮件测试' message['Subject'] = Header(subject, 'utf-8') try: smtpObj = smtplib.SMTP() smtpObj.connect(mail_host, 25) # 25 为 SMTP 端口号 smtpObj.login(mail_user,mail_pass) smtpObj.sendmail(sender, receivers, message.as_string()) print ("邮件发送成功") except smtplib.SMTPException: print ("Error: 无法发送邮件")
|
这样执行,会报错
smtplib.SMTPDataError: (554, 'DT:SPM 126 smtp5,jtKowAD3MJz2c1JXLcK2AA--.52114S2 1465021431,please see http://mail.163.com/help/help_spam_16.htm?ip=123.114.121.110&hostid=smtp5&time=1465021431')
解决办法就是指定收发件人
1 2
| message['From'] = from_account message['To'] = to_account
|
p.s 网易邮箱客户端默认授权码是关闭的,直接执行python调用会失败,要先进客户端,把客户授权码打开
位置:设置-客户端授权密码
设置完成之后,登录密码就使用你设置的授权码