Python: Get Gmail server with smtplib never ends

十年热恋 提交于 2019-12-11 05:29:12

问题


I simply tried:

>>> import smtplib
>>> server = smtplib.SMTP('smtp.gmail.com:587')

in my Python interpreter but the second statement never ends.

Can someone help?


回答1:


You might find that you need a login and password as a prerequisite to a successful login-in.
Try something like this:

import smtplib
ServerConnect = False
try:
    smtp_server = smtplib.SMTP('smtp.gmail.com','587')
    smtp_server.login('your_login', 'password')
    ServerConnect = True
except SMTPHeloError as e:
    print "Server did not reply"
except SMTPAuthenticationError as e:
    print "Incorrect username/password combination"
except SMTPException as e:
    print "Authentication failed"

If you get "connection unexpected closed" try changing the server line to:

smtp_server = smtplib.SMTP_SSL('smtp.gmail.com','465')

Be aware: Google may block sign-in attempts from some apps or devices that do not use modern security standards. Since these apps and devices are easier to break into, blocking them helps keep your account safe. See:https://support.google.com/accounts/answer/6010255?hl=en

Gmail settings:

SMTP Server (Outgoing Messages)     smtp.gmail.com  SSL     465     
    smtp.gmail.com  StartTLS    587
IMAP Server (Incoming Messages)     imap.gmail.com  SSL     993    
    Please make sure, that IMAP access is enabled in the account settings.
Login to your account and enable IMAP.
You also need to enable "less secure apps" (third party apps) in the Gmail settings:
https://support.google.com/accounts/answer/6010255?hl=en
See also: How to enable IMAP/POP3/SMTP for Gmail account

If all else fails trying to ping gmail.com from the command line.



来源:https://stackoverflow.com/questions/39516200/python-get-gmail-server-with-smtplib-never-ends

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!