python try / SMTPLib除外的问题
作者:互联网
我使用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
显然,socket.py中的“ create_connection”会爆炸.这有它自己的try /除了块:
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"
我没有得到的是-追溯显示了引发err的调用.显然err不是None,因此必须将其设置为_:….作为error的一部分.因此,最初处理了错误,但是作为处理程序的一部分,创建了一个副本(err)-随后将其复制在try / except块之外引发-因此未处理.然后,该未处理的错误应“传递回”调用堆栈(get_socket没有try / except块,也没有connect或__init__-因此,在try / except块之外的是create_connection中原始错误,错误副本, err应该确定然后“层叠”回到我的runClient函数中的try / except块吗?
解决方法:
在@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部分….每次都很好.最终版本如下.除了我在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"
莫名其妙,但松了一口气!谢谢安德烈!
标签:smtplib,error-handling,try-catch,python 来源: https://codeday.me/bug/20191028/1956013.html