Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I hold a SMTP connection open with smtplib and Python?

I need to check the timeout of a SMTP-Server, but my socket just closes. What am I doing wrong? Here is my test for it:

#!/usr/bin/python
import smtplib
import time
import datetime
import socket
socket.setdefaulttimeout(1800)


now = time.time()
server = smtplib.SMTP()
server.set_debuglevel(1)
server.connect('mx.foo.bar','25')
(code,resp) = server.docmd('NOOP')
then = time.time()

print then-now

Lets hope this works.

like image 758
leto Avatar asked Sep 13 '25 11:09

leto


1 Answers

Well, I haven't found any method to hold a smtp connection open with smtplib.

But, if you want to reuse a connection without closing (yes, opening a connection takes time, 2-3 secs), you can test the connection first. To do this, issue a NOOP command and test for status == 250. If not, then you can open a connection and send out your mail. And you can choose to not quit() the connection until you are done.

import smtplib

def create_conn():
    conn = smtplib.SMTP('smtp.gmail.com', 587)
    ...
    return conn

def is_connected(conn):
    try:
        status = conn.noop()[0]
    except:  # smtplib.SMTPServerDisconnected
        status = -1
    return True if status == 250 else False
like image 81
Ethan Avatar answered Sep 16 '25 01:09

Ethan