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

It's OK to reuse the connection to send email, but the server may terminate the connection at any time, that depends on server's strategy. So just catch the corresponding error and reconnect again

Is it OK to connect smtp server once and send many emails in a long period?
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()

using the above code, I test sending 10 emails using the same connection, but got Exception below, I think that may be related to the safety strategy of target smtp server.

[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 connecti

here is the code from my college, but I thougt it's not much effecient 'cause it'll connect smtp server and login every time, and just send one mail..., so how about I connect smtp and login for the first time once the service started, and using this long connection to send mail aferwards?

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()


Click Here to Visit

What's Your Reaction?

like
0
dislike
0
love
0
funny
0
angry
0
sad
0
wow
0