Search code examples
pythonpython-3.xserversmtplocalserver

SMTPNotSupportedError when trying to send email using SMTP with Python


I am trying to run a script which sends an email using Python from a local server (not gmail, office etc.)

My code is the following:

    message = MIMEMultipart()
    message['From'] = 'noreply@test.com'
    message['To'] = 'hello@test.com'
    msg_body = 'test'

    server = SMTP('123.456.78.901', 01)
    server.starttls() 

    server.sendmail(message['From'], message['To'], msg_body)
    server.quit()

An error occurs in the following line:

server.starttls()

Which states the following:

SMTPNotSupportedError: STARTTLS extension not supported by server.

This piece of code worked perfectly fine when I was sending the email via a gmail server, using the following line of code:

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

However I am now trying to have the email sent directly from a local server. Any help is appreciated, thanks!


Solution

  • That simply means your local server does not support STARTTLS. So don't try to do that. TLS encryption only makes sense when you are connecting over an insecure public network.

    You have already established a connection to the SMTP server. If you remove the server.starttls() line from your program, you will proceed with the existing connection, without encryption.

    (STARTTLS is a bit of a hack; unlike other SSL-based protocols, you start with an unencrypted connection, then upgrade to establish an encrypted connection over the same circuit if the server supports it and the client requests it.)

    However, the third argument to sendmail should be a valid SMTP message, not a random free-form string. You already have a message, but you are only attempting to send a different string.

        server.sendmail(message['From'], message['To'], msg.as_string())  # not msg_body
    

    Probably better still to upgrade to the Python 3.6+ library and use EmailMessage instead of MIMEMultipart to start building the message. The Python email examples documentation has all the details.