连接一次smtp服务器,长期发送多封邮件可以吗?

Is it OK to connect smtp server once and send many emails in a long period?

这是我大学的代码,但我认为它不是很有效,因为它每次都会连接 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()
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')

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