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?

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