4

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.

import os
import platform
import smtplib

#Define our SMTP server. We use gmail. Try to connect.
try:
    server = smtplib.SMTP()
    print "Defined server"
    server.connect("smtp.gmail.com",465)
    print "Connected"
    server.ehlo()
    server.starttls()
    server.ehlo()
    print "Complete Initiation"
except Exception, R:
    print R
Xeneficus
  • 133
  • 1
  • 12

1 Answers1

6

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:

server = smtplib.SMTP()
print("Defined server")
server.connect("smtp.gmail.com",587)
print("Connected")
server.ehlo()
server.starttls()
server.ehlo()

or 465 with SMTP_SSL.

server = smtplib.SMTP_SSL()
print("Defined server")
server.connect("smtp.gmail.com", 465)
print("Connected")
server.ehlo()
  • 2
    When I execute the previous code in my personal machine, it works fine, however, if I try to run it in my virtual machine (at work, SUSE Linux Enterp Srv 11 SP4) it never gets connected, instead it throws an connection timed out error, any help? **I don't have admin rights** – Mike Apr 05 '20 at 17:45
  • 1
    @Mike I guess the outbound port has been blocked on the server. – Antti Haapala -- Слава Україні Apr 06 '20 at 11:04