smtplib timeout

Alan Kennedy alanmk at hotmail.com
Tue Jul 25 12:21:40 EDT 2006


[Stuart D. Gathman]
> I need to set a timelimit for the operation of
> smtplib.sendmail.  It has to be thread based, because pymilter uses
> libmilter which is thread based.  There are some cookbook recipies which
> run a function in a new thread and call Thread.join(timeout).  This
> doesn't help, because although the calling thread gets a nice timeout
> exception, the thread running the function continues to run.  In fact, the
> problem is worse, because even more threads are created.

Have you tried setting a default socket timeout, which applies to all
socket operations?

Here is a code snippet which times out for server connections. Timeouts
should also work for sending and receiving on sockets that are already
open, i.e. should work for the smtplib.sendmail call.

==============================
import socket
import smtplib

dud_server = '192.168.1.1'
timeout_value = 1.0 # seconds

socket.setdefaulttimeout(timeout_value)

print "connecting to server: %s" % dud_server
try:
  connection = smtplib.SMTP(dud_server)
except socket.timeout:
  print "server timed out"
==============================

HTH,

--
alan kennedy
------------------------------------------------------
email alan:              http://xhaus.com/contact/alan




More information about the Python-list mailing list