如果您的用例一次发送一条消息,对我来说最正确的解决方案是为每条消息创建一个新的 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()