Erik Grigoryan
Erik Grigoryan

Reputation: 21

SMTP Python Connection unexpectedly closed

Hello to all on my question page.

So what happened was I wanted to create a program to email myself automatically with a spam email I made at once every hour just to learn some cool python libraries, but when I run the program, it gives me an error. The error is right below my code. I have blocked the password because it is private and yeah. Before you guys say it is because the password is wrong, it is not because if it were, it would say "Authentication failed"

My Code:

#imports
import smtplib

port = 465

smtp_server = "mail.gmx.com"
email = "[email protected]"
password = "****************"
target = "[email protected]"
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()

My Error:

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

Any help will be appreciated

Upvotes: 1

Views: 12343

Answers (1)

mti2935
mti2935

Reputation: 12027

According to https://support.gmx.com/pop-imap/imap/windowsmailapp.html, clients sending outgoing mail through mail.gmx.com should connect on port 587 and use starttls. So, first try changing your script to connect on port 587 instead of port 465. Also, you'll need to send the ehlo command before the starttls command, then again after the starttls command. The following should work:

import smtplib

to='[email protected]'
fromname='sender'
fromemail='[email protected]'
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()

Upvotes: 1

Related Questions