views:

322

answers:

2

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.

+2  A: 

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)
Nick Presta
+3  A: 

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.

Mike Graham