Search code examples
pythonpython-3.xemailsmtplib

Send e-mail with python error "Connection unexpectedly closed"


I want to send a E-mail using python using this code but the final result is a "Connection unexpectedly closed" error:

import smtplib

sender_email = "example@gmail.com"
rec_email = "example2@gmail.com"
password = "password"
message = "Test message using python !"

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender_email, password)
server.sendmail(sender_email, rec_email, message)

This is the error:

    raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed

Solution

  • It might be that the bigger email providers (I would believe this includes Gmail) block 'unsafe applications' from accessing the server.

    You might want to try to login to sender_email and there should be an option somewhere that allows 'unsafe applications to access', or something similar.

    I had a similar problem when doing the same thing with my Yahoo account, and this basically solved the problem.