python我是否可以检查SMTP服务器是否已断开连接(以便我可以再次连接?)
我使用的是python我是否可以检查SMTP服务器是否已断开连接(以便我可以再次连接?),python,smtplib,Python,Smtplib,我使用的是smtplib,我正在从我的应用程序发送通知电子邮件。然而,我注意到,有时(特别是在发送邮件之间有大量空闲时间的情况下)我会收到SMTPServerDisconnected错误 我想这有两种解决方案(但我不知道) 增加发送邮件之间的空闲时间 当连接断开时重新连接 我认为第二种解决方案似乎更优雅。但是我怎么能做到呢 编辑:我正在添加代码 from smtplib import SMTP smtp = SMTP() smtp.connect('smtp.server.com') smtp.
smtplib
,我正在从我的应用程序发送通知电子邮件。然而,我注意到,有时(特别是在发送邮件之间有大量空闲时间的情况下)我会收到SMTPServerDisconnected
错误
我想这有两种解决方案(但我不知道)
from smtplib import SMTP
smtp = SMTP()
smtp.connect('smtp.server.com')
smtp.login('username','password')
def notifyUser():
smtp.sendmail(from_email, to_email, msg.as_string())
如果您的用例一次只发送一条消息,我认为最正确的解决方案是为每条消息创建一个新的SMTP会话:
from smtplib import SMTP
smtp = SMTP('smtp.server.com')
def notifyUser(smtp, smtp_user, smtp_password, from_email, to_email, msg):
smtp.login(smtp_user, smtp_password)
smtp.sendmail(from_email, to_email, msg.as_string())
smtp.quit()
如果SMTP服务器不要求您进行身份验证(常见情况),则可以进一步简化为:
from smtplib import SMTP
smtp = SMTP('smtp.server.com')
def notifyUser(smtp, from_email, to_email, msg):
smtp.sendmail(from_email, to_email, msg.as_string())
smtp.quit()
如果一次发送多封邮件很常见,并且您希望通过对邮件组重新使用相同的SMTP会话来优化这种情况(如果您不需要登录SMTP服务器,可以如上所述进行简化):
是的,您可以检查连接是否打开。为此,发出NOOP命令并测试status==250。如果没有,请在发送邮件之前打开连接
def test_conn_open(conn):
try:
status = conn.noop()[0]
except: # smtplib.SMTPServerDisconnected
status = -1
return True if status == 250 else False
def send_email(conn, from_email, to_email, msg):
if not test_conn_open(conn):
conn = create_conn()
conn.sendmail(from_email, to_email, msg.as_string())
return conn # as you want are trying to reuse it.
请注意,您这样做是因为打开连接(例如使用gmail)需要花费2-3秒的时间。随后,要优化发送多封您手头上可能有的电子邮件,您还应该遵循Pedro的回复(最后一部分)。您是否使用
SMTP.sendmail
发送电子邮件?它应该封装从connect
开始的所有低级命令。或者你是想保持SMTP会话打开,并将其重新用于多封电子邮件?我已经添加了你要求的代码。希望这能进一步澄清这个问题。:-)谢谢那就行了。还有一件事。根据文档,是smtp.close()
还是smtp.quit()
?请使用with
语句,而不是显式quit
@PolymorphicPotato:请注意,对with
语句的支持仅添加到.smtp.close()上的smtp
类中只需关闭套接字,而不通知服务器停止。它没有返回值。smtp.quit()将quit命令发送到服务器,然后调用.close()。它返回服务器响应,这样您就可以知道它已经结束了。除非您的编写方式需要评估docmd(“QUIT”)方法的结果,否则只需使用QUIT();这是一件负责任的事情。
def test_conn_open(conn):
try:
status = conn.noop()[0]
except: # smtplib.SMTPServerDisconnected
status = -1
return True if status == 250 else False
def send_email(conn, from_email, to_email, msg):
if not test_conn_open(conn):
conn = create_conn()
conn.sendmail(from_email, to_email, msg.as_string())
return conn # as you want are trying to reuse it.