我想发送多封个性化电子邮件,并将每封电子邮件的各个部分尽可能有效地合并到一个模板中。
以下是我用来实现此目的的当前代码的示例:
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来实现这种形式的邮件合并?
谢谢!