I’m writing a small python script to send an email, but my code isn’t even getting past smtp connection. I’m using the following code, but I never see “Connected”. Additionally, I’m not seeing an exception thrown, so I think it’s hanging on something.
JavaScript
x
17
17
1
import os
2
import platform
3
import smtplib
4
5
#Define our SMTP server. We use gmail. Try to connect.
6
try:
7
server = smtplib.SMTP()
8
print "Defined server"
9
server.connect("smtp.gmail.com",465)
10
print "Connected"
11
server.ehlo()
12
server.starttls()
13
server.ehlo()
14
print "Complete Initiation"
15
except Exception, R:
16
print R
17
Advertisement
Answer
Port 465 is for SMTPS; to connect to SMTPS you need to use the SMTP_SSL; however SMTPS is deprecated, and you should be using 587 (with starttls
). (Also see this answer about SMTPS and MSA).
Either of these will work: 587 with starttls
:
JavaScript
1
8
1
server = smtplib.SMTP()
2
print("Defined server")
3
server.connect("smtp.gmail.com",587)
4
print("Connected")
5
server.ehlo()
6
server.starttls()
7
server.ehlo()
8
or 465 with SMTP_SSL
.
JavaScript
1
6
1
server = smtplib.SMTP_SSL()
2
print("Defined server")
3
server.connect("smtp.gmail.com", 465)
4
print("Connected")
5
server.ehlo()
6