python使用SMTP发送qq或sina邮件

python使用qq邮箱(个人邮箱)发送邮件需开启qq邮箱的SMTP服务

在设置中开启pop3/SMTP服务,返回的密码就是之后代码中登录使用账户密码(在完整代码中标识了出来)

之后出现如下错误

复制代码 代码如下:
smtplib.SMTPAuthenticationError: (530, 'Error: A secure connection is requiered(such as ssl). More information at http://service.mail.qq.com/cgi-bin/help?id=28')

错误说要开ssl发送邮件

在原来的代码上添加上如下三行代码即可

smtpObj.ehlo()
smtpObj.starttls()
smtpObj.ehlo()

完整代码如下

import smtplib
from email.mime.text import MIMEText
from email.header import Header

# 第三方 SMTP 服务
mail_host = "smtp.qq.com" # 设置服务器,qq的SMTP服务host
mail_user = "xxx@qq.com" # 用户名(须修改)
mail_pass = "xxxxxxxxxxxxxxxx" # 此处为在qq开启SMTP服务时返回的密码 (须修改)

sender = 'xxx@qq.com'  # 同用户名 (须修改)
receivers = ['xxx@qq.com'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

message = MIMEText('...', 'plain', 'utf-8')
message['From'] = Header("第一封python测试邮件", 'utf-8')
message['To'] = Header("测试", 'utf-8')

try:
 subject = 'Python SMTP 邮件测试'
 message['Subject'] = Header(subject, 'utf-8')
 smtpObj = smtplib.SMTP()
 smtpObj.connect(mail_host, 25) # 25 为 SMTP 端口号
 smtpObj.ehlo()
 smtpObj.starttls()
 smtpObj.ehlo()
 smtpObj.login(mail_user, mail_pass)
 smtpObj.sendmail(sender, receivers, message.as_string())
 print "邮件发送成功"
except smtplib.SMTPException :
 print "Error: 无法发送邮件"

在使用sina邮箱开启SMPT服务后使用python发送信息卡在了如下错误#不是很理解

smtplib.SMTPDataError: (553, 'Envolope sender mismatch with header from..')

成功的例子是

import smtplib
server = "smtp.sina.com"
fromaddr= "xxx@sina.com" #须修改
toaddr = "xxx@qq.com" #须修改
msg = """
to:%s
from:%s
Hello,I am smtp server
""" %(toaddr,fromaddr)
s = smtplib.SMTP(server)
s.set_debuglevel(1)
s.login("xxx@sina.com","xxx")  #须修改
s.sendmail(fromaddr,toaddr,msg)

报错的例子是

import smtplib
from email.mime.text import MIMEText
from email.header import Header
server = "smtp.sina.com"
fromaddr= "xxx@sina.com"
toaddr = "xxx@qq.com"

message = MIMEText('...', 'plain', 'utf-8')
message['From'] = Header(fromaddr, 'utf-8')
message['To'] = Header("toaddr", 'utf-8')
subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject, 'utf-8')

s = smtplib.SMTP(server)
s.set_debuglevel(1)
s.login("xxx@sina.com","xxx")
s.sendmail(fromaddr,toaddr,message)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: