2

我有一个应用程序将发送数千封电子邮件。我最初的计划是遍历每条记录并一次发送一封电子邮件,然后从记录的 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>
4

1 回答 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()   

使用上面的代码,您的正文模板只需在取消订阅链接中包含“模板”标签(示例中为“{email}”)。该示例还使用实际的电子邮件地址,但如果您愿意,可以根据它生成一个唯一标识符。

于 2014-04-10T01:10:42.607 回答