开发者

How can I catch for a connection timeout error in Python's SMTPlib?

The error being thrown is:

error: [Errno 110] Connection timed out

I'm not sure what to except for?

    try:
        smtpObj = smtplib.SMTP('smtp.example.com')
        smtpObj.starttls()
        smtpObj.login('user','pass')
        smtpObj.sendmail(sender, receivers, message)
        print "Successfully sent email"
    except smtplib.SMTPException('Error: unable to send email"'):
        pass
    except smtplib.socket.error ('Error: could not connect to server'):开发者_运维知识库
        pass

Thanks.


You need to provide the exception class, not an instance thereof. That is to say, the code should look like

try:
    smtpObj = smtplib.SMTP('smtp.example.com')
    smtpObj.starttls()
    smtpObj.login('user','pass')
    smtpObj.sendmail(sender, receivers, message)
    print "Successfully sent email"
except smtplib.SMTPException: # Didn't make an instance.
    pass
except smtplib.socket.error:
    pass

The second exception, smtplib.socket.error, seems to be the applicable one to catch that error. It is usually accessed directly from the socket module import socket, socket.error.

Note that I said that was what the code "should" look like, and that's sort of an exaggeration. When using try/except, you want to include as little code as possible in the try block, especially when you are catching fairly general errors like socket.error.


I believe socket.error should work but if you post the code you're using, we can help you better. smtplib.SMTPConnectError should also be of interest.

Try something like this:

try:
    server = smtplib.SMTP("something.com")
except (socket.error, smtplib.SMTPConnectError):
    print >> stderr, "Error connecting"
    sys.exit(-1)


OSError is the base class for smtplib.SMTPConnectError, socket.timeout, TimeoutError, etc. Therefore, you should catch OSError if you want to handle them all:

try:
    ...
except OSError:
    ...

See: https://bugs.python.org/issue20903

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜