Ombwayo Michael
Ombwayo Michael

Reputation: 13

Django send bulk emails

I am working on a service to send bulk emails in django. I have this method which is working well with celery

@shared_task(bind=True)
def send_mails(self,saved_id):
    text = BroadCast.objects.get(id=saved_id)
    attendees = EventAttendee.objects.filter(event__id=text.id)
    message = text.body
    subject = text.subject
    document = text.attachment
    recipient_list=[]
    for attend in attendees:

        text_content = render_to_string(template_text, {'name': attend.client_name, 'message':message})
        html_content = render_to_string(template_html, {'name': attend.client_name,'message':message})

        mail.send(
            [attend.client_email],
            email_from,
             subject=subject,
             html_message=html_content,
             attachments = {str(document):document}
        )

my challenge is that if i have for examples 1000 attendees, I will have to open 1000 connections which I believe is a very bad.

How can I restructure it so that I only open one connection and be able to send 1000 emails..

Upvotes: 0

Views: 1063

Answers (2)

Nader Alexan
Nader Alexan

Reputation: 2222

From Django's docs

django.core.mail.send_mass_mail() is intended to handle mass emailing.

Since you are sending html, you would need an extra step, consider the following piece of code from this stackoverflow answer:

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)

Upvotes: 2

heyhugo
heyhugo

Reputation: 1015

Then you probably want to use send_mass_mail

only one connection to the mail server would be opened

So construct a tuple of messages for all the emails you want to send. (The linked official documentation does a good job explaining usage)

Upvotes: 0

Related Questions