2010-11-05 48 views
1

我有一个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会更安全吗?

回答

1

Also would it be safer to use /usr/sbin/sendmail rather than smtplib?

从视图的处理的消息队列和一个队列浇道重试的点。是的,sendmail或其他本地MTA可以为您处理此问题。

Any thoughts on how to proceed debugging this?

数据包捕获。使用wireshark捕获smtp流量,看看发生了什么。您有很多广泛的异常处理,并不一定会向您显示确切的错误。

相关问题