我有一個python腳本,每天定期使用smtplib發送幾組電子郵件(不同的地址與不同的內容)。比較頻繁(比如說同時發送多個電子郵件的批次大約是1/5),我得到一個IOError(errno:broken pipe)。我嘗試重新設置並退出SMTP服務器,然後再次連接到服務器並嘗試重新發送,但如果第一次失敗(具有相同的例外),則總是失敗。 SMTP服務器由大學維護,並且應該可靠(並且只要您在Intranet上就允許登錄電子郵件)。間歇性smtp斷開的管道(errno 32)
忽略下面的代碼(缺乏DRY)的醜陋,任何人都可以建議一個更可靠的方法來連接?
我創建一個名爲EmailSet類將發送一批具有成員函數send_emails幾個電子郵件:
class EmailSet(object):
...
def send_emails(self):
try: # Connect to server
server = smtplib.SMTP(smtp_server_name_str, 25)
server.set_debuglevel(self.verbose)
server.ehlo()
for email in self.email_set:
try: # send 1st mail
logging.debug("Sending email to %r" % email.recipients)
response_dict = server.sendmail(email.fromaddr, email.recipients, email.msg_str())
logging.info("Sent email to %r" % email.recipients)
except Exception as inst:
logging.error('RD: %r' % response_dict)
logging.error("Email Sending Failed")
logging.error("%r %s" % (type(inst), inst))
try: # send second mail
logging.info("Second Attempt to send to %r" % email.recipients)
try:
server.rset()
server.quit()
except:
pass
time.sleep(60) # wait 60s
server = smtplib.SMTP(smtp_server_name_str, 25)
server.set_debuglevel(self.verbose)
server.ehlo()
response_dict = server.sendmail(email.fromaddr, email.recipients, email.msg_str())
logging.info("Sent email to %r (2nd Attempt)" % email.recipients)
except Exception as inst:
try:
logging.error('RD: %r' % response_dict)
except:
pass
logging.error("Second Attempt Email Sending Failed")
except:
logging.debug("Can't connect to server")
finally:
logging.debug("Reseting and Quitting Server")
server.rset()
server.quit()
logging.debug("Successfully Quit Server")
return True
如何進行調試這有什麼想法? stmp服務器不是由我維護的,但應該維護良好(用於約10k人組織)。我最初在發送每封電子郵件後連接並斷開與smtpserver的連接,但這比此方法產生更多的錯誤。
同時使用/ usr/sbin/sendmail而不是smtplib會更安全嗎?