python2.7发送邮件失败之——代码问题

使用python2.7发送邮件,代码如下:

from  email.header import Header
from email.mime.text import MIMEText
import smtplib
#发送邮箱
sender='[email protected]'
password='123456'
#接受邮箱
receiver='[email protected]'

smtpserver='smtp.126.com'

subject='python email test'
msg=MIMEText('下雨了,大家关好窗户','plain','utf-8')
msg['Subject']=Header(subject,'utf-8')
try:
smtp=smtplib.SMTP()
smtp.connect(smtpserver)
smtp.login(sender,password)
smtp.sendmail(sender,receiver,msg.as_string())
smtp.quit()
print "邮件发送成功"
except smtplib.SMTPException:
print "Error:无法发邮件"
运行时提示:
Error:无法发邮件
<class 'smtplib.SMTPException'>
解决办法:
在try的上面加上以下两行代码,问题解决:
msg['From']=sender
msg['to']=receiver



猜你喜欢

转载自www.cnblogs.com/Ladylittleleaf/p/9719791.html