我想发送多封个性化电子邮件,每个电子邮件的不同部分尽可能高效地合并到一个模板中。
下面是我用来实现这一点的当前代码示例:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formatdate
name_from = 'Test'
email_from ='test_sender@mail.com'
subject = 'Test E-Mail to {}'
message = 'Test E-Mail message to {}'
recipient_emails = ['andrew@mail.com','sally@mail.com','thomas@mail.com']
recipient = ['Andrew','Sally','Thomas']
for recipient_email,recipient in zip(recipient_emails,recipient):
msg = MIMEMultipart('alternative')
msg['From'] = '{} <{}>'.format(name_from,email_from)
msg['To'] = '{} <{}>'.format(email_from)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject.format(recipient)
msg1 = MIMEText(message.format(recipient),'plain')
msg.attach(msg1)
smtpObj = smtplib.SMTP_SSL('smtp.mail.com',111,timeout=None)
smtpObj.login(email_from,'password')
smtpObj.sendmail(email_from,recipient_email,msg.as_string())
smtpObj.quit()
这是可行的,但它所做的是一个接一个地发送多封电子邮件,但我想知道是否有一种更有效/更pythonic的方法可以在python中使用smtplib来实现这种形式的邮件合并?
谢谢!