Search code examples
pythonsmtplib

python smtplib set timeout


I am trying write small application to send an email every day with the status of my server. I am using smtplib, but am having a little problem. I don't know how to set the connection timeout! I am trying with smtp.setdefaulttimeout(30) but it does not work.

def connect(host,user,password)
  try:
    smtp = smtplib.SMTP(host)
        smtp.login(user, password)
        code = smtp.ehlo()[0]
        if not (200 <= code <= 299):
            code = smtp.helo()[0]
 except:
     pass

how can I set the connection timeout in this function?


Solution

  • From Python 2.6 you can set a timeout in SMTP library (official documentation):

    class smtplib.SMTP([host[, port[, local_hostname[, timeout]]]])
    

    "if not specified, the global default timeout setting will be used"

    If you use an older version of Python (< 2.6 ) you need to set a socket default timeout:

    import socket
    socket.setdefaulttimeout(120)
    

    For me worked fine.