代码之家  ›  专栏  ›  技术社区  ›  OD1995

python在smtplib.smtp(“smtp.gmail.com”,587)上冻结

  •  1
  • OD1995  · 技术社区  · 7 年前

    我正在尝试使用gmail创建一个发送电子邮件的脚本。但是,当运行以下行时,我的代码将冻结:

    smtplib.SMTP("smtp.gmail.com", 587)
    

    这是在我的用户名和密码被输入之前,所以这与我的gmail帐户无关。为什么会这样?我正在使用Python3.6.3

    完整代码如下:

    import smtplib
    
    # Specifying the from and to addresses
    
    fromaddr = 'XXX@gmail.com'
    toaddrs  = 'YYY@gmail.com'
    
    # Writing the message (this message will appear in the email)
    
    msg = 'Enter you message here'
    
    # Gmail Login
    
    username = 'XXX@gmail.com'
    password = 'PPP'
    
    # Sending the mail  
    
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(username,password)
    server.sendmail(fromaddr, toaddrs, msg)
    server.quit()
    
    2 回复  |  直到 7 年前
        1
  •  3
  •   Phil    7 年前

    这很可能是防火墙或类似的问题。在出现问题的计算机上,尝试在命令行上运行此命令:

    ping smtp.gmail.com
    

    假设这有效,那么尝试:

    telnet smtp.gmail.com 587
    

    我假设一台linux机器有这个命令。你需要适应别人。如果连接,请键入 ehlo list 命令应该显示一些信息。类型 quit 退出。

    如果这不起作用,那就检查你的iptables。

    sudo iptables -L
    

    这要么会显示出 ACCEPT all 在下面 Chain INPUT 或者,如果没有,你需要确保你接受的是与以下对象建立的关系:

    ACCEPT     all  --  anywhere             anywhere             state RELATED,ESTABLISHED
    

    输出链通常是打开的,但您也应该检查它。

    如果您在aws上,请检查您的安全组没有阻止传出连接。

        2
  •  1
  •   Ajay Shewale    7 年前

    使用 server.ehlo() 在你的密码里。

    代码段:

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    

    对于身份验证错误: http://joequery.me/guides/python-smtp-authenticationerror/

    添加以下代码段并再次运行。

    try:
        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.ehlo()
        server.starttls()
        server.login(username,password)
        server.sendmail(fromaddr, toaddrs, msg)
        server.close()
        print 'successfully sent the mail'
    except:
        print "failed to send mail"
    
    推荐文章