如果您的用例一次发送一条消息,我认为最正确的解决方案是为每条消息创建一个新的SMTP会话:from smtplib import SMTP
smtp = SMTP('smtp.server.com')
def notifyUser(smtp, smtp_user, smtp_password, from_email, to_email, msg):
smtp.login(smtp_user, smtp_password)
smtp.sendmail(from_email, to_email, msg.as_string())
smtp.quit()
如果您的SMTP服务器不要求您自己进行身份验证(常见情况),则可以进一步简化为:from smtplib import SMTP
smtp = SMTP('smtp.server.com')
def notifyUser(smtp, from_email, to_email, msg):
smtp.sendmail(from_email, to_email, msg.as_string())
smtp.quit()
如果一次要发送多个邮件是常见的,并且您希望通过对邮件组重用同一个SMTP会话来优化此情况(如果不需要登录到SMTP服务器,可以像上面这样简化):from smtplib import SMTP
smtp = SMTP('smtp.server.com')
def notifyUsers(smtp, smtp_user, smtp_password, from_to_msgs):
"""
:param from_to_msgs: iterable of tuples with `(from_email, to_email, msg)`
"""
smtp.login(smtp_user, smtp_password)
for from_email, to_email, msg in from_to_msgs:
smtp.sendmail(from_email, to_email, msg.as_string())
smtp.quit()