使用EmailMultiAlternatives发送send_mass_emails

时间:2011-09-28 13:12:34

标签: django

我尝试构建简报应用程序,并希望通过一个连接发送50封电子邮件。 send_mass_mail()看起来很完美,但我无法弄清楚我如何将其与EmailMultiAlternatives结合使用。

这是我的代码,只发送一封带有一个连接的电子邮件:

html_content = render_to_string('newsletter.html', {'newsletter': n,})               
text_content = "..."                      
msg = EmailMultiAlternatives("subject", text_content, "from@bla", ["to@bla"])                                      
msg.attach_alternative(html_content, "text/html")                                                                                                                                                                               
msg.send()  

上面的代码和send_mass_mail的工作示例会很棒,谢谢!

6 个答案:

答案 0 :(得分:30)

send_mass_mail()改写使用EmailMultiAlternatives

from django.core.mail import get_connection, EmailMultiAlternatives

def send_mass_html_mail(datatuple, fail_silently=False, user=None, password=None, 
                        connection=None):
    """
    Given a datatuple of (subject, text_content, html_content, from_email,
    recipient_list), sends each message to each recipient list. Returns the
    number of emails sent.

    If from_email is None, the DEFAULT_FROM_EMAIL setting is used.
    If auth_user and auth_password are set, they're used to log in.
    If auth_user is None, the EMAIL_HOST_USER setting is used.
    If auth_password is None, the EMAIL_HOST_PASSWORD setting is used.

    """
    connection = connection or get_connection(
        username=user, password=password, fail_silently=fail_silently)
    messages = []
    for subject, text, html, from_email, recipient in datatuple:
        message = EmailMultiAlternatives(subject, text, from_email, recipient)
        message.attach_alternative(html, 'text/html')
        messages.append(message)
    return connection.send_messages(messages)

答案 1 :(得分:15)

无法直接将send_mass_mail()与EmailMultiAlternatives一起使用。但是,根据the Django documentation,send_mass_mail()只是一个使用EmailMessage类的包装器。 EmailMultiAlternatives是EmailMessage的子类。 EmailMessage具有“连接”参数,允许您指定在向所有收件人发送邮件时使用的单个连接 - 即与send_mass_mail()提供的功能相同。您可以使用get_connection()功能获取由settings.py中的SMTP settings定义的SMTP连接。

我认为以下(未经测试的)代码应该有效:

from django.core.mail import get_connection, EmailMultiAlternatives

connection = get_connection() # uses SMTP server specified in settings.py
connection.open() # If you don't open the connection manually, Django will automatically open, then tear down the connection in msg.send()

html_content = render_to_string('newsletter.html', {'newsletter': n,})               
text_content = "..."                      
msg = EmailMultiAlternatives("subject", text_content, "from@bla", ["to@bla", "to2@bla", "to3@bla"], connection=connection)                                      
msg.attach_alternative(html_content, "text/html")                                                                                                                                                                               
msg.send() 

connection.close() # Cleanup

答案 2 :(得分:2)

我采用了混合方法,向用户发送纯文本和HTML消息,并为每个用户个性化消息。

我是从Sending multiple emails od Django文档部分开始的。

from django.conf import settings
from django.contrib.auth.models import User
from django.core import mail
from django.core.mail.message import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context

...

connection = mail.get_connection()
connection.open()
messages = list()

for u in users:
    c = Context({ 'first_name': u.first_name, 'reseller': self,})
    subject, from_email, to = 'new reseller', settings.SERVER_EMAIL, u.email
    text_content = plaintext.render(c)
    html_content = htmly.render(c)
    msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
    msg.attach_alternative(html_content, "text/html")
    messages.append(msg)

connection.send_messages(messages)
connection.close()

答案 3 :(得分:2)

这就是我执行任务的方式(经过测试的代码):

from html2text import html2text

from django.utils.translation import ugettext as _
from django.core.mail import EmailMultiAlternatives, get_connection


def create_message(subject, message_plain, message_html, email_from, email_to,
                   custom_headers=None, attachments=None):
    """Build a multipart message containing a multipart alternative for text (plain, HTML) plus
    all the attached files.
    """
    if not message_plain and not message_html:
        raise ValueError(_('Either message_plain or message_html should be not None'))

    if not message_plain:
        message_plain = html2text(message_html)

    return {'subject': subject, 'body': message_plain, 'from_email': email_from, 'to': email_to,
            'attachments': attachments or (), 'headers': custom_headers or {}}


def send_mass_html_mail(datatuple):
    """send mass EmailMultiAlternatives emails
    see: http://stackoverflow.com/questions/7583801/send-mass-emails-with-emailmultialternatives
    datatuple = ((subject, msg_plain, msg_html, email_from, email_to, custom_headers, attachments),)
    """
    connection = get_connection()
    messages = []
    for subject, message_plain, message_html, email_from, email_to, custom_headers, attachments in datatuple:
        msg = EmailMultiAlternatives(
            **create_message(subject, message_plain, message_html, email_from, email_to, custom_headers, attachments))
        if message_html:
            msg.attach_alternative(message_html, 'text/html')
        messages.append(msg)

    return connection.send_messages(messages)

答案 4 :(得分:0)

这是一个简洁的版本:

from django.core.mail import get_connection, EmailMultiAlternatives

def send_mass_html_mail(subject, message, html_message, from_email, recipient_list):
    emails = []
    for recipient in recipient_list:
        email = EmailMultiAlternatives(subject, message, from_email, [recipient])
        email.attach_alternative(html_message, 'text/html')
        emails.append(email)
    return get_connection().send_messages(emails)

答案 5 :(得分:0)

当您发送多封/大量/大量电子邮件时,建立和关闭SMPT /任何连接都是很昂贵的过程,您必须重用连接,而不是为每个收件人创建和销毁连接。

您必须创建一个连接并立即发送所有电子邮件。

from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.utils.html import strip_tags
from django.core import mail

def send_bulk_email(emails_list, subject, context, template, from_email):
    html_content = render_to_string(template, context)
    text_content = strip_tags(html_content)
    emails = []
    for recipient in emails_list:
        email = EmailMultiAlternatives(subject, text_content, from_email, [recipient])
        email.attach_alternative(html_content, "text/html")
        emails.append(email)
    connection = mail.get_connection()
    return connection.send_messages(emails)