在群发邮件时创建退订链接
我有一个应用程序需要发送成千上万封电子邮件。最开始我打算一个一个地处理每条记录,逐个发送邮件,并根据记录的UUID来生成退订链接。为了加快发送邮件的速度,我改用了EmailMultiAlternative和get_connection(),这样只需要建立一个上下文就可以了。
email = EmailMultiAlternatives()
email.subject = email_script.subject
email.from_email = DEFAULT_FROM_EMAIL
template = get_template('email/email_blast_template.html')
......
body = template.render(context)
connection = get_connection()
connection.open()
email.bcc = list(recipients)
email.body = body
email.attach_alternative(body, "text/html")
email.connection = connection
email.send()
connection.close()
有没有办法让我访问每封正在发送的邮件的电子邮件地址,以便我可以生成退订链接?在request.META中有没有存储相关信息?我在查看里面的内容时遇到了一些困难。
If you wish to unsubscribe click <a href={% url unsubscribe email.uuid }}>here</a>
1 个回答
0
我不太明白你说的那种情况是怎么可能的。你在示例代码中生成的邮件是无法根据每个收件人进行定制的,因为它只是发出了一封邮件(也就是说,你没有为每个收件人生成独特的内容)。我认为唯一的解决办法就是像你最开始提到的那样,为每个收件人创建单独的邮件。
要做到这一点,你可以只打开和关闭一次连接,甚至只渲染一次模板,但实际准备和发送邮件时可以用一个循环来处理。这种方法应该比每次都重新生成内容或者为每封邮件重新打开连接要高效得多。例如:
template = get_template('email/email_blast_template.html')
body = template.render(context)
connection = get_connection()
connection.open()
for recipient in recipients:
email = EmailMultiAlternatives()
email.subject = email_script.subject
email.from_email = DEFAULT_FROM_EMAIL
email.bcc = recipient
email.body = body.replace('{email}', recipient)
email.attach_alternative(body.replace('{email}', recipient), "text/html")
email.connection = connection
email.send()
connection.close()
使用上面的代码,你的邮件正文模板只需要在退订链接中包含“template”标签(示例中的“{email}”)。这个示例还使用了实际的电子邮件地址,但如果你愿意,也可以基于这个地址生成一个独特的标识符。