首先自己參考教程寫的沒有成功:
import smtplib
import email.mime.multipart
import email.mime.text
msg=email.mime.multipart.MIMEMultipart()
msg['from']='2764896xx@qq.com'
msg['to']='10750490xx@qq.com'
msg['subject']='test'
content="just try"
txt=email.mime.text.MIMEText(content)
msg.attach(txt)
smtp=smtplib
smtp=smtplib.SMTP()
smtp.connect('smtp.qq.com','465')
smtp.login('2764896xx@qq.com','password')//password是在開啟qq的smtp服務器時給的口令
smtp.sendmail('2764896xx@qq.com','10750490xx@qq.com',str(msg))
smtp.quit()
然后借用http://www.lxweimin.com/p/0f8c5e4e7054哥們的寫法成功了:
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
my_sender='2764896xx@qq.com' # 發件人郵箱賬號
my_pass = 'password' # 發件人郵箱密碼(當時申請smtp給的口令)
my_user='10750490xx@qq.com' # 收件人郵箱賬號,我這邊發送給自己
def mail():
ret=True
try:
msg=MIMEText('哈哈哈哈哈,王xx,收到郵件請回復!','plain','utf-8')
msg['From']=formataddr(["發件人昵稱",my_sender]) # 括號里的對應發件人郵箱昵稱、發件人郵箱賬號
msg['To']=formataddr(["收件人昵稱",my_user]) # 括號里的對應收件人郵箱昵稱、收件人郵箱賬號
msg['Subject']="郵件主題-測試" # 郵件的主題,也可以說是標題
server=smtplib.SMTP_SSL("smtp.qq.com", 465) # 發件人郵箱中的SMTP服務器,端口是465
server.login(my_sender, my_pass) # 括號中對應的是發件人郵箱賬號、郵箱密碼
server.sendmail(my_sender,[my_user,],msg.as_string()) # 括號中對應的是發件人郵箱賬號、收件人郵箱賬號、發送郵件
server.quit()# 關閉連接
except Exception:# 如果 try 中的語句沒有執行,則會執行下面的 ret=False
ret=False
return ret
ret=mail()
if ret:
print("郵件發送成功")
else:
print("郵件發送失敗")
后面嘗試了下,把1中的
smtp=smtplib.SMTP()
改為
smtp=smtplib.SMTP_SSL()
則郵件發送成功,具體原因還不知道。
注意:不能將文件名叫做email.py,否則會報 ImportError: No module named mime.text
因為在代碼開頭使用了 from email.mime.text import MIMEText
如果文件名叫email.py,呵呵,你懂得。。。