smtplib timeout

Alan Kennedy alanmk at hotmail.com
Tue Jul 25 15:13:12 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.

[Alan Kennedy]
>> Have you tried setting a default socket timeout, which applies to all
>> socket operations?

[Stuart D. Gathman]
> Does this apply to all threads, is it inherited when creating threads, or
> does each thread need to specify it separately?

It is a module level default, which affects all socket operations after
the socket.setdefaulttimeout() call, regardless of whether they are in
threads or not.

So you only need to call it once, probably before any other processing
takes place.

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

dud_server = '192.168.1.1'
timeout_value = 1.0 # seconds

socket.setdefaulttimeout(timeout_value)

def do_connect(tno):
  print "Thread%d: connecting to server: %s" % (tno, dud_server)
  try:
    connection = smtplib.SMTP(dud_server)
  except socket.timeout:
    print "Thread%d: server timed out" % tno

for x in range(5):
  t = threading.Thread(target=do_connect, args=(x,))
  t.start()
=================================================

C:\>python smtp_timeout.py

Thread0: connecting to server: 192.168.1.1
Thread1: connecting to server: 192.168.1.1
Thread2: connecting to server: 192.168.1.1
Thread3: connecting to server: 192.168.1.1
Thread4: connecting to server: 192.168.1.1
Thread0: server timed out
Thread1: server timed out
Thread2: server timed out
Thread4: server timed out
Thread3: server timed out

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




More information about the Python-list mailing list