Problem sending Mail with smtplib

Hello ,

i want to send an email automatic with pyhton. This is my Code:

#send email
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
server = smtplib.SMTP('smtp.ionos.de', 465)
try:
name="Mein Name" #You need to fill the name here
server.connect('smtp.ionos.de', 465)
server.starttls()
server.ehlo()
server.login("[info@test.de](mailto:info@test.de)","Passwort")
TOADDR = "[test@web.de](mailto:test@web.de)"
FromADDR = "[info@test.de](mailto:info@test.de)"
msg = MIMEMultipart('alternative')
msg['Subject'] = "Testbetreff"
msg['From'] = FromADDR
msg['To'] = TOADDR
#The below is email body
html = """\
<html>
<body>
<p><span style="color: rgb(0,0,0);">Dear {0},</span></p>
<p>
your email body
</p>
<p>Kind Regards,<br />
Your name ....
</p>
</body>
</html>
""".format(name.split()[0])
msg.attach(MIMEText(html, 'html'))
server.sendmail(FromADDR, TOADDR, msg.as_string())
except Exception as e:
# Print any error messages to stdout
print(e)
finally:
server.quit()

i get this error:
Traceback (most recent call last):
File “C:\Users\MeinName\Downloads\emailsendenTest3.py”, line 5, in
server = smtplib.SMTP(‘smtp.ionos.de’, 465)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “C:\Program Files\Python312\Lib\smtplib.py”, line 255, in init
(code, msg) = self.connect(host, port)
^^^^^^^^^^^^^^^^^^^^^^^^
File “C:\Program Files\Python312\Lib\smtplib.py”, line 343, in connect
(code, msg) = self.getreply()
^^^^^^^^^^^^^^^
File “C:\Program Files\Python312\Lib\smtplib.py”, line 405, in getreply
raise SMTPServerDisconnected(“Connection unexpectedly closed”)
smtplib.SMTPServerDisconnected: Connection unexpectedly closed

i use Python 3.12

This is failing in the initial connection. That limits what could be wrong.

Sometimes a server will block your IP address if you’ve made too many connection attempts in too short a period of time. You may need to wait a few hours and try again.

You should also double check that you are connecting to the correct port for "smtp.ionos.de

Though this is not relevant to your current problem, you should remove the connect call:

server.connect('smtp.ionos.de', 465)

The documentation indicates that the SMTP constructor calls it for you.

1 Like

i am also facing the same issue if you get the the solution plz guide me that how can fix it