SMTP Python连接意外关闭

时间:2019-01-13 04:42:17

标签: python email smtplib

在我的问题页面上向大家问好。

所以发生了什么事,我想创建一个程序以每小时发送一次的垃圾邮件自动向自己发送电子邮件,只是为了学习一些很酷的python库,但是当我运行该程序时,它给了我一个错误。错误就在我的代码下面。我已经封锁了密码,因为它是私人的,是的。在你们之前说这是因为密码错误,不是因为如果密码错误,它将说“身份验证失败”

我的代码:

#imports
import smtplib

port = 465

smtp_server = "mail.gmx.com"
email = "kbodfkghset232gvja23@gmx.us"
password = "****************"
target = "gerik700@gmail.com"
message = """
Subject: Test

This is a test message
"""

#login to server to send email
server = smtplib.SMTP(host=smtp_server, port=port)
try:
    server.starttls()
    server.login(email, password)
    server.set_debuglevel(1)
    server.ehlo()
    #sending message
    server.sendmail(email, target, message)


except Exception as e:
    print(e)
finally:
    server.quit()

我的错误:

Traceback (most recent call last):
  File "Email_Program.py", line 17, in <module>
    server = smtplib.SMTP(host=smtp_server, port=port)
  File "C:\Program Files (x86)\Python37-32\lib\smtplib.py", line 251, in __init__
    (code, msg) = self.connect(host, port)
  File "C:\Program Files (x86)\Python37-32\lib\smtplib.py", line 338, in connect
    (code, msg) = self.getreply()
  File "C:\Program Files (x86)\Python37-32\lib\smtplib.py", line 394, in getreply
    raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

根据https://support.gmx.com/pop-imap/imap/windowsmailapp.html,通过mail.gmx.com发送外发邮件的客户端应在端口587上连接并使用starttls。因此,首先尝试更改脚本以在端口587而不是端口465上进行连接。此外,您需要在ehlo命令之前发送starttls命令,然后在starttls之后再次发送命令。以下应该起作用:

import smtplib

to='to@to.com'
fromname='sender'
fromemail='from@from.com'
subject='this is the subject'
body='this is the message body'

message=''
message+= "To: " + to + "\n"
message+= "From: \"" + fromname + "\" <" + fromemail + ">\n"
message+= "Subject: " + subject + "\n"
message+= "\n"
message+= body

mailserver = smtplib.SMTP('mail.gmx.com',587)
mailserver.ehlo()
mailserver.starttls()
mailserver.ehlo()  #again
mailserver.login('username', 'password')
mailserver.sendmail(fromemail, to, message)
mailserver.quit()