今天學習使用郵箱自動化辦公的過程中run時一直出現如下錯誤;smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted.
1 import smtplib 2 from smtplib import SMTP_SSL 3 from email.mime.text import MIMEText 4 from email.mime.multipart import MIMEMultipart 5 from email.header import Header 6 7 host_server = 'smtp.gmail.com' 8 9 10 sender_gmail = 'xxxxxxxx@gmail.com' 11 pwd = 'xxxxxxxxxxx' #郵箱密碼 12 13 sender_gmail_mail = 'xxxxxxxx@gmail.com' #發件人 14 receiver = 'xxxxxxxxxxx@qq.com' #收件人 15 16 mail_title = 'python自動化' #郵件標題 17 18 mail_content = '你好這是使用python進行測試' #正文 19 20 msg = MIMEMultipart() #郵件主體 21 msg['subject'] = Header(mail_title,'utf_8') 22 msg['From'] = sender_gmail_mail 23 msg['To'] = Header('test','UTF-8') 24 msg.attach(MIMEText(mail_content,'plain','utf-8')) #郵件正文 plain無格式 25 26 stmp = SMTP_SSL(host_server) #ssl登錄 27 28 stmp.login(sender_gmail,pwd) 29 stmp.sendmail(sender_gmail_mail,receiver,msg.as_string()) 30 stmp.quit()
解決方案
網上查找資料需要進行如下設置在谷歌郵箱中
1.確定賬號未被限制,在瀏覽器上能正常登陸gmail.
2.在設置->轉發和 POP/IMAP 中開啟pop和imap,兩個都要開啟.
3.開啟賬號的二步驗證:帳戶和導入->更改密碼恢復選項 查看兩步驗證行,若是停止狀態則點擊根據指標開啟兩步驗證
4.生成16位應用專用密碼:https://security.google.com/settings/security/apppasswords
在這里根據提示生成一個應用專用密碼,生成成功后復制密碼然第5步。
5.帳戶和導入->更改密碼 把你的原始密碼更改為剛生成的16位密碼。
把密碼填入程序中,現在smtp可以發送成功了
必須開啟兩步驗證,及使用專用密碼登錄,否則報錯
參考
原文鏈接:https://blog.csdn.net/bichir/article/details/51506474