我使用Python的SMTPLib编写了一个简单的SMTP客户端。只是尝试添加一些错误处理 - 特别是在这个例子中,当连接的目标服务器不可用时(例如,指定了错误的IP!)
目前,追溯看起来像这样:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "smtplib_client.py", line 91, in runClient
try:
File "/usr/local/lib/python2.7/smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
File "/usr/local/lib/python2.7/smtplib.py", line 311, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/local/lib/python2.7/smtplib.py", line 286, in _get_socket
return socket.create_connection((host, port), timeout)
File "/usr/local/lib/python2.7/socket.py", line 571, in create_connection
raise err
socket.error: [Errno 111] Connection refused
很清楚,它是&#34; create_connection&#34;在socket.py去爆炸。这有它自己的try / except块:
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
af, socktype, proto, canonname, sa = res
sock = None
try:
sock = socket(af, socktype, proto)
if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
sock.settimeout(timeout)
if source_address:
sock.bind(source_address)
sock.connect(sa)
return sock
except error as _:
err = _
if sock is not None:
sock.close()
if err is not None:
raise err
else:
raise error("getaddrinfo returns an empty list")
我的runClient()函数如下所示:
def runClient(configName = 'default', testFile = './test.xml'):
cliCfg = getClientConfig(configName)
print cliCfg.find('logfile').text
# startLogger(cliCfg.find('logfile').text)
clientCert = cliCfg.find('cert').text
clientKey = cliCfg.find('key').text
serverHost = cliCfg.find('serverhost').text
serverPort = int(cliCfg.find('serverport').text)
myMail = MailMessageHandler()
msgSrc = myMail.readMessageSource(testFile)
allMsgs = myMail.processMessages(msgSrc)
inx = 1
for msg in allMsgs:
validMsg = True
requiredKeys = ('ehlo', 'sndr', 'rcpt', 'body')
for msgItems in requiredKeys:
if len(msg[msgItems]) == 0:
validMsg = False
if validMsg:
try:
server = smtplib.SMTP(serverHost, serverPort)
server.ehlo(msg['ehlo'])
thisSender = msg['sndr']
thisRecipient = msg['rcpt']
thisMessage = MIMEText(msg['body'])
thisMessage['To'] = email.utils.formataddr(('', thisRecipient))
thisMessage['From'] = email.utils.formataddr(('', thisSender))
thisMessage['Subject'] = msg['subject']
thisMessage['Message-id'] = email.utils.make_msgid()
now = datetime.now()
day = now.strftime('%a')
date = now.strftime('%d %b %Y %X')
thisMessage['Date'] = day + ', ' + date + ' -0000'
if msg['tls'].lower() == 'true':
server.starttls('certs/client/client.key', 'certs/client/client.crt')
logging.info ("Message: " + thisMessage['Message-id'] + " to be sent over TLS")
server.sendmail(thisSender, thisRecipient.split(","), thisMessage.as_string())
logging.info ("Message: " + thisMessage['Message-id'] + " sent successfully to " + serverHost + ":" + cliCfg.find('serverport').text)
logging.info ("Message: " + thisMessage['Message-id'] + " had sender: " + thisMessage['From'])
logging.info ("Message: " + thisMessage['Message-id'] + " had recipient(s): " + thisMessage['To'])
except socket.error as e:
print "Could not connect to server - is it down? ({0}): {1}".format(e.strerrror)
except:
print "Unknown error:", sys.exc_info()[0]
finally:
server.quit()
else:
print "Improperly formatted source mail - please check"
我得不到的是 - 回溯显示对raise err
的调用。很明显err
不是None,所以它必须设置为except error as _:
的一部分....所以最初处理错误,但作为处理程序的一部分,创建了一个副本({{ 1}}) - 随后在try / except块之外引发 - 因此未处理。然后,这个未处理的错误应该被传回&#34;调用堆栈(err
没有try / except块,也没有get_socket
或connect
- 因此在{{1}中的原始__init__
的try / except块之外那么,错误的副本error
肯定会&#34;级联&#34;回到我的runClient函数中的try / except块?
答案 0 :(得分:4)
继来自@AndreySobolev的支持后,我得到了以下简单代码:
import smtplib, socket
try:
mylib = smtplib.SMTP("127.0.0.1", 25)
except socket.error as e:
print "could not connect"
所以我接着回到我的smtplib_client.py,然后阻止注释掉大部分的“try”部分。这工作得很好...所以一点一点,我恢复了越来越多的尝试部分....每一次它工作正常。最终版本如下。除了我在except socket.error
处理程序中执行的操作之外,我不能说我知道我已更改的任何内容 - 除了我还添加了server = None
以阻止finally
部分工作。哦,我还必须在我的导入列表中添加“socket”。没有这个,我可以理解除了没有正确处理 - 但我不明白为什么它根本没有发射,甚至产生“未定义”的错误....奇怪!
工作代码:
def runClient(configName = 'default', testFile = './test.xml'):
cliCfg = getClientConfig(configName)
print cliCfg.find('logfile').text
# startLogger(cliCfg.find('logfile').text)
clientCert = cliCfg.find('cert').text
clientKey = cliCfg.find('key').text
serverHost = cliCfg.find('serverhost').text
serverPort = int(cliCfg.find('serverport').text)
myMail = MailMessageHandler()
msgSrc = myMail.readMessageSource(testFile)
allMsgs = myMail.processMessages(msgSrc)
inx = 1
for msg in allMsgs:
validMsg = True
requiredKeys = ('ehlo', 'sndr', 'rcpt', 'body')
for msgItems in requiredKeys:
if len(msg[msgItems]) == 0:
validMsg = False
if validMsg:
try:
server = None
server = smtplib.SMTP(serverHost, serverPort)
server.ehlo(msg['ehlo'])
thisSender = msg['sndr']
thisRecipient = msg['rcpt']
thisMessage = MIMEText(msg['body'])
thisMessage['To'] = email.utils.formataddr(('', thisRecipient))
thisMessage['From'] = email.utils.formataddr(('', thisSender))
thisMessage['Subject'] = msg['subject']
thisMessage['Message-id'] = email.utils.make_msgid()
now = datetime.now()
day = now.strftime('%a')
date = now.strftime('%d %b %Y %X')
thisMessage['Date'] = day + ', ' + date + ' -0000'
if msg['tls'].lower() == 'true':
server.starttls('certs/client/client.key', 'certs/client/client.crt')
logging.info ("Message: " + thisMessage['Message-id'] + " to be sent over TLS")
server.sendmail(thisSender, thisRecipient.split(","), thisMessage.as_string())
logging.info ("Message: " + thisMessage['Message-id'] + " sent successfully to " + serverHost + ":" + cliCfg.find('serverport').text)
logging.info ("Message: " + thisMessage['Message-id'] + " had sender: " + thisMessage['From'])
logging.info ("Message: " + thisMessage['Message-id'] + " had recipient(s): " + thisMessage['To'])
except socket.error as e:
logging.error ("Could not connect to " + serverHost + ":" + cliCfg.find('serverport').text + " - is it listening / up?")
except:
print "Unknown error:", sys.exc_info()[0]
finally:
if server != None:
server.quit()
else:
print "Improperly formatted source mail - please check"
困惑,但松了一口气!谢谢安德烈!