【问题标题】:Is it OK to connect smtp server once and send many emails in a long period?连接一次smtp服务器,长期发很多邮件可以吗?
【发布时间】:2021-03-04 23:30:42
【问题描述】:

这是我大学的代码,但我认为它不是很有效,因为它每次都会连接 smtp 服务器并登录,并且只发送一封邮件...,那么我连接 smtp 并登录如何服务启动后第一次使用这个长连接发送邮件?

def send_email(receiver, subject, mail_body):
    msg = MIMEText(mail_body, _subtype='html', _charset='utf-8')
    msg['Subject'] = Header(subject, 'utf-8')
    msg['From'] = XXXX@xx.com
    msg['To'] = receiver

    try:
        smtp = smtplib.SMTP()
        smtp.connect(xxxx.com)
        smtp.login(user, password)
        smtp.sendmail(XXXX@xx.com, receiver.split(','), msg.as_string())
    except Exception:
        logger.error('Send email failed: %s' % traceback.format_exc())
    finally:
        smtp.quit()

【问题讨论】:

  • 在完成所有发送工作后,尽可能多地拨打smtp.sendmail(...) 并拨打smtp.quit()。或者干脆不把smtp.quit()放到函数里,拆分成另一个函数,重写程序。
  • 如果我从不退出连接会怎样?一年?
  • 服务器是空闲的,可以随时终止连接,所以它可能不会有那么长时间的空闲连接。如果你想重用一个连接,你必须实现代码,根据错误决定它们是临时的(在这种情况下实现重试,mavbe 有等待期)还是永久的(例如错误的凭据);在这种情况下中止并通知用户错误代码和消息。另见en.wikipedia.org/wiki/List_of_SMTP_server_return_codes
  • 谢谢,这正是我想要的,也许你可以把这个 cmets 放在答案中。

标签: python email smtp


【解决方案1】:

重用连接发送邮件是可以的,但是服务器可能随时终止连接,这取决于服务器的策略。所以只要捕获相应的错误并重新连接即可。

【讨论】:

    【解决方案2】:
    def send_email(receiver, subject, mail_body):
       try:
           smtp = smtplib.SMTP()
           smtp.connect(xxxx.com)
           smtp.login(user, password)
           # for test           
           for i in range (10):
               smtp.sendmail(XXXX@xx.com, receiver.split(','), msg.as_string())
    
       except Exception:
        logger.error('Send email failed: %s' % traceback.format_exc())
       finally:
        smtp.quit()
    

    使用上面的代码,我测试了用同一个连接发送10封邮件,但是得到了下面的异常,我认为这可能与目标smtp服务器的安全策略有关。

    [2021-03-01 15:56:25,386] [ERROR] [125:MainThread] [send_email.py:47] [send_email]:send email failed: Traceback (most recent call last):
    File "send_email.py", line 41, in send_email
    smtp.sendmail(EmailAccount, email_receiver.split(','), msg.as_string())
    File "/usr/lib/python2.7/smtplib.py", line 737, in sendmail
    raise SMTPSenderRefused(code, resp, from_addr)
    SMTPSenderRefused: (450, 'Requested mail action not taken: too much delivery in this connection', 'xxxx@xxxx.com')
    

    【讨论】:

      猜你喜欢
      • 2020-04-19
      • 1970-01-01
      • 1970-01-01
      • 2015-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-04
      相关资源
      最近更新 更多