我有以下代码,这是我在我的程序中使用的电子邮件类的一部分。目前我正在运行退出功能,无论是否在连接功能中建立了与SMTP服务器的连接。我知道我可以在发送电子邮件之后将退出函数放在try语句中,但是我想弄清楚如何编写代码来说明“如果与服务器的连接是打开的,则关闭它”。在Python中编写它的最佳方法是什么?
谢谢!
def connect(self, headers, msg):
try:
self.server.starttls()
try:
self.server.login(self.usrname,self.pswd)
try:
self.server.sendmail(self.sendfrom, self.sendto, headers + "\r\n\r\n" + msg)
except Exception as sendmailfail:
print(sendmailfail)
except Exception as emailfail:
print (emailfail)
except Exception as error:
print(error)
def quit(self):
self.server.quit()
print("The SMTP connection is closed")
first = GmailSmpt('x','y','z','zz')
x , y = first.message()
first.connect(x,y)
first.quit()
答案 0 :(得分:4)
您需要完成"Errors and Exceptions" section of the tutorial。
try:
possibly_fail()
except ...:
handle_exception()
else:
no_exceptions()
finally:
always_run_this()