send_mass_emails with EmailMultiAlternatives
Asked Answered
I

6

27

I try to build a newsletter application and want to send 50 emails with one connection. send_mass_mail() looks perfect but I can't figure out how I call this in combination with EmailMultiAlternatives.

This is my code that sends only one email with one connection:

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()  

a working example with the code above and send_mass_mail would be great, thanks!

Ismaelisman answered 28/9, 2011 at 13:12 Comment(0)
E
22

It's not possible to directly use send_mass_mail() with EmailMultiAlternatives. However, according to the Django documentation, send_mass_mail() is simply a wrapper that makes use of the EmailMessage class. EmailMultiAlternatives is a subclass of EmailMessage. EmailMessage has a 'connection' parameter allowing you to specify a single connection to use when sending the message to all recipients - i.e. the same functionality as provided by send_mass_mail(). You can use the get_connection() function to obtain an SMTP connection as defined by the SMTP settings in settings.py.

I believe that the following (untested) code should work:

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
Exteroceptor answered 28/9, 2011 at 13:40 Comment(3)
Thanks for your answer but every user can see all the other users in the "TO" field. I want only one recipient per mail.Ismaelisman
Use 'bcc' e.g.: msg = EmailMultiAlternatives("subject", text_content, "from@bla", ["to@bla"], bcc=["to2@bla", "to3@bla"], connection=connection)Exteroceptor
I don't get why you need to manually open and close the smtp connection when you're not iterating or creating multiple instances of EmailMultiAlternatives.Krucik
T
55

That is send_mass_mail() rewritten to use 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)
Thiol answered 18/4, 2012 at 17:52 Comment(3)
How to use this? I added this Funtion in mypy script but it cant find get_connection.Emeritaemeritus
Hey @Stillmatic1985, I've just added the import line in the code aboveThiol
that should be merged to DjangoChart
E
22

It's not possible to directly use send_mass_mail() with EmailMultiAlternatives. However, according to the Django documentation, send_mass_mail() is simply a wrapper that makes use of the EmailMessage class. EmailMultiAlternatives is a subclass of EmailMessage. EmailMessage has a 'connection' parameter allowing you to specify a single connection to use when sending the message to all recipients - i.e. the same functionality as provided by send_mass_mail(). You can use the get_connection() function to obtain an SMTP connection as defined by the SMTP settings in settings.py.

I believe that the following (untested) code should work:

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
Exteroceptor answered 28/9, 2011 at 13:40 Comment(3)
Thanks for your answer but every user can see all the other users in the "TO" field. I want only one recipient per mail.Ismaelisman
Use 'bcc' e.g.: msg = EmailMultiAlternatives("subject", text_content, "from@bla", ["to@bla"], bcc=["to2@bla", "to3@bla"], connection=connection)Exteroceptor
I don't get why you need to manually open and close the smtp connection when you're not iterating or creating multiple instances of EmailMultiAlternatives.Krucik
H
2

I followed a mixed approach, sending to users both plain text and html messages and personalizing messages for every user.

I started from the section Sending multiple emails od Django documentation.

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()
Hagiography answered 14/8, 2014 at 10:36 Comment(1)
Django 1.10 - Don't need to open and close connection manually. From Django docs connection.send_messages(messages) ----- send_messages() opens a connection on the backend, sends the list of messages, and then closes the connection again.Kerrin
S
2

This is how I do the task (tested code):

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: https://mcmap.net/q/495923/-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)
Shantae answered 5/11, 2015 at 15:42 Comment(0)
S
2

Here's a succinct version:

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)
Symer answered 2/11, 2017 at 21:2 Comment(0)
K
1

When you are sending multiple/mass/bulk emails, establishing and closing SMPT/any connection is an expensive process, you have to reuse the connection instead of creating and destroying the connection for every recipient.

You have to create a single connection and send all the emails at once.

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)
Kos answered 19/9, 2020 at 19:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.