kingcope
kingcope

Reputation: 1141

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?

Upvotes: 2

Views: 22544

Answers (3)

nagylzs
nagylzs

Reputation: 4178

Python 3.7 has an extra timeout parameter that can be used:

https://docs.python.org/3/library/smtplib.html#smtplib.SMTP

This parameter is not present in Python 2

Upvotes: 1

Michał Niklas
Michał Niklas

Reputation: 54292

While internally smtplib uses socket then you can use socket.setdefaulttimeout() before connecting to host:

def connect(host,user,password):
    try:
        socket.setdefaulttimeout(2 * 60)
        smtp = smtplib.SMTP(host)
        ...

Upvotes: 1

user4018366
user4018366

Reputation:

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.

Upvotes: 9

Related Questions