如何在Python的SMTPlib中捕获连接超时错误?

时间:2010-03-28 03:22:53

标签: python error-handling smtplib

抛出的错误是:

error: [Errno 110] Connection timed out

我不确定除了什么?

    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

感谢。

3 个答案:

答案 0 :(得分:4)

您需要提供异常类,而不是其实例。也就是说,代码应该看起来像

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

第二个例外smtplib.socket.error似乎是适用于捕获该错误的例外。它通常直接从套接字模块import socketsocket.error

访问

请注意,我说这就是代码“应该”的样子,这有点夸张。使用try / except时,您希望在try块中包含尽可能少的代码,尤其是当您捕获socket.error等相当常见的错误时。

答案 1 :(得分:2)

我相信socket.error应该有用,但如果你发布了你正在使用的代码,我们可以帮助你更好。 smtplib.SMTPConnectError也应引起关注。

尝试这样的事情:

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

答案 2 :(得分:0)

OSErrorsmtplib.SMTPConnectErrorsocket.timeoutTimeoutError等的基类。因此,如果要处理所有OSError,则应捕获try: ... except OSError: ...

model_json = 
{
     modelId: 239475,
     type: BPMN,
     # some other diagram information,
     childShapes: [
          {
               stencil: Pool,
               title: Company XY,
               positionData: { some stuff },
               ...
               childShapes: [
                    {
                         stencil: Lane,
                         title: Engineering,
                         attributes: {
                              head: Peter,
                              costCenter: T534                              
                         },
                         childShapes: [
                              {
                                   stencil: Task,
                                   title: Review Code,
                                   attributes: {
                                        executive: Mark
                                   },
                              },
                              {
                                   stencil: Task,
                                   title: Push New Commit,
                                   attributes: {
                                        executive: Michael
                                   },
                              },
                              ...
                         ]
                    }, 
                    ...
               ]
          },
          ...
     ]
     ...
}

请参阅:https://bugs.python.org/issue20903