Python smtplib:Gmail有效,但只是“有时”

时间:2017-01-30 21:43:59

标签: python smtp gmail smtplib

我写了一个简单的脚本来通过Gmail SMTP服务器发送电子邮件。代码如下:

import smtplib
msg = 'Hello World!'
server = smtplib.SMTP('smtp.gmail.com', 587) #port 465 or 587
server.ehlo()
server.starttls()
server.ehlo()
server.login('username@googlemail.com','password')
server.sendmail('username@googlemail.com','username@googlemail.com', msg)
server.close()

有时它有效,有时我会收到错误。它是什么原因?我已将Gmail配置为接受安全性较低的应用。如果错误发生,我收到以下消息:

Traceback (most recent call last):
  File "email.py", line 31, in <module>
    server.login('username@googlemail.com','password')
  File "/usr/lib/python3.5/smtplib.py", line 729, in login
    raise last_exception
  File "/usr/lib/python3.5/smtplib.py", line 720, in login
    initial_response_ok=initial_response_ok)
  File "/usr/lib/python3.5/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=AKgnsbvQ\n5.7.14 DBMYWMukfjghdjfkghfjkhjkfhgjkdhgdfjkghekjghekjgndjkSm5lAOfEpP2Nt\n5.7.14 QihtNp5izjfghjjkjhgbhjbGHJVHJVjhvhjbhjbhjDZwhJFV-FiyvI-OGW\n5.7.14 jcpmHcQAcOR8e8G0zOfdugjhfdjd-sdfiugdsjfdsrthdfewrzjhg-shgv2HxmgWpZg3Z\n5.7.14 4G1ENiAlgiEnrkXyRbTG3frjZZdPg> 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 g40sm24698383wrg.19 - gsmtp')

我在互联网上找不到任何帮助。非常感谢您的每一条建议。

1 个答案:

答案 0 :(得分:2)

答案建议首先启用对安全性较低的应用的访问权限。如果这不起作用,您可以尝试访问该页面上提供的链接:https://www.google.com/accounts/DisplayUnlockCaptcha

这可以启用访问。