python使用SMTP發送qq或sina郵件,pythonsmtp
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 smtplibfrom email.mime.text import MIMETextfrom email.header import Header# 第三方 SMTP 服務mail_host = "smtp.qq.com" # 設定伺服器,qq的SMTP服務hostmail_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 smtplibserver = "smtp.sina.com"fromaddr= "xxx@sina.com" #須修改toaddr = "xxx@qq.com" #須修改msg = """to:%sfrom:%sHello,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 smtplibfrom email.mime.text import MIMETextfrom email.header import Headerserver = "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)
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。