In some cases you may have an unencrypted connection to a SMTP server, which you need to upgrade to an encrypted connection. In this video, you’ll learn how to do that!
Opportunistic Encryption With starttls()
00:00 In the last video, you initiated a connection that was secure from the start. Sometimes you won’t be able to do this and you need to create an unencrypted connection and then upgrade it to an encrypted one.
This is where this
.starttls() method comes into play. To do this, you’ll be able to keep most of these parameters the same, except now change this
port here to
587, because this is what Google will be listening for for this type of connection.
which will just be
smtp.SMTP(), then pass in the
smtp_server and the
port. Note that there’s no SSL here. Now you’ll say hello to the server using
.ehlo(), which is kind of like
.helo(), but it’s an extended version, and that’s the
And it’s probably a good idea to acknowledge yourself to the server again, so let’s just do
server.ehlo(). And now that the connection is encrypted, it’s safe to login. So just like before, you can call
server.login(), pass in your
sender email and your
password, just like that.
And this is actually a kind of interesting error. You can see that the
'server' is not defined error occurred at line 25—which, if you go down, is inside this
finally block—but we defined what
server was up here.
And there we go!
It worked! So now you know two different ways to make a secure connection to an SMTP server. When we actually start sending the emails, we’ll be creating connections that are secure from the start, like in the previous video.
03:28 I like doing that because it’s a little bit less code to type out and I just feel a little better about it. The big thing, though, is now you’re ready to start sending some actual emails with Python. Thanks for watching.
Become a Member to join the conversation.