質問

i trying write small application for send email every day whit status of my server, i am use smtplib, bat have little problem i don't know can set connection timeout ! im try whit smtp.setdefaulttimeout(30) bat 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 set connection timeout to this function ? thanks

役に立ちましたか?

解決

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.

他のヒント

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)
        ...

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top