我试图在python中使用SMTP来发送gmail,但它失败了

时间:2016-07-19 17:53:59

标签: email smtplib

这是我的脚本:

from email.mime.text import MIMEText
import smtplib
msg=MIMEText('hi, send by python.....','plain','utf-8')
from_addr='user@gmail.com'
passowrd='psw'
to_addr='user@gmail.com'
s=smtplib.SMTP('smtp.gmail.com',587)
s.login(from_addr,password)
s.sendmail(from_addr, [to_addr], msg.as_string())

运行时出现错误:

Traceback (most recent call last):
File "C:\Users\bicuilin\Desktop\begin.py", line 17, in <module>
s.login(from_addr, password)
File "C:\Users\bicuilin\AppData\Local\Programs\Python\Python35\lib\smtplib.py", line 696, in login
"SMTP AUTH extension not supported by server.")
smtplib.SMTPNotSupportedError: SMTP AUTH extension not supported by server.

我试着解决它。我在下面添加代码:

...
s.ehlo()
s.starttls()
s.login(from_addr, password)
s.sendmail(from_addr, [to_addr], msg.as_string())
s.quit()

这里出现错误我真的不明白:

Traceback (most recent call last):
File "C:\Users\bicuilin\Desktop\begin.py", line 20, in <module>
s.login(from_addr, password)
File "C:\Users\bicuilin\AppData\Local\Programs\Python\Python35\lib\smtplib.py", line 729, in login
raise last_exception
File "C:\Users\bicuilin\AppData\Local\Programs\Python\Python35\lib\smtplib.py", line 720, in login
initial_response_ok=initial_response_ok)
File "C:\Users\bicuilin\AppData\Local\Programs\Python\Python35\lib\smtplib.py", line 641, in auth
raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbvK\n5.7.14 1h8JVCjH3EdlnG4ye0St7PIWFsYfjtuO_qovrt6r-spvSMGNbeCxbpXuo3HfqK535dgJy2\n5.7.14 Tjz1zrEZI8QqRc0GyXD2t3Xa0rj_MVHbzX5fM1f2zgbFyoP9YUbwCyaRD5guosxyv3HcS8\n5.7.14 fvB_ORP6_djncJPUwGw98BDCTo2pw3RSvgYHAvS_xO-T97Hw2z35g3AKPW9Bb5E9EcpAgg\n5.7.14 pewpsm0VngKqoxhYhtFwHBW_8s1ig> Please log in via your web browser and\n5.7.14 then try again.\n5.7.14  Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 a67sm1686251qkc.24 - gsmtp')

2 个答案:

答案 0 :(得分:1)

你必须使用SMTP_SSL类,它可以工作(在这里测试)。无需starttls(无论如何都不会工作)

from email.mime.text import MIMEText
import smtplib
msg=MIMEText('hi, send by python.....','plain','utf-8')
from_addr='user@gmail.com'
password='psw'
to_addr='user@gmail.com'
s=smtplib.SMTP_SSL('smtp.gmail.com')
s.login(from_addr,password)
s.sendmail(from_addr, [to_addr], msg.as_string())

答案 1 :(得分:-1)

Less Secure Apps - gmail

有同样的问题。在Gmail上允许安全性较低的应用后,让它正常运行!