Prabesh Shrestha
Prabesh Shrestha

Reputation: 2742

send_mass_mail in background django

I am using send_mass_email to send emails to a list of users. It is working fine until I send it to more than 200 emails at a time. Actually emails are being delivered without a problem. But I am getting time-out error from nginx because it takes long( more than 2 mins) to send emails to all 200+ emails.

What is the best way to run send_mass_mail in background ?

Upvotes: 3

Views: 1596

Answers (4)

mossplix
mossplix

Reputation: 3865

You can make it a management command and then setup a periodic cron job to send out the emails refer management command docs

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 600059

You might want to look into the django-mailer project, which encapsulates this functionality - it does this via crons, rather than using a task queue. I've been using it for a while with good results.

Upvotes: 3

Burhan Khalid
Burhan Khalid

Reputation: 174758

You need to move the tasks to the background (so they don't block the web process). One of the most popular ways to do this is to use a messaging/task queue.

Celery is one of the most popular distributed task queues, and coupled with the django-celery application makes this trivial.

First you need to setup celery (which is as simple as pip install -U celery); and one of the many messaging brokers that it supports. The most popular one is RabbitMQ; but for quick and dirty set ups you can also use your existing database as a message broker.

Finally, since this is a common problem solved by celery+django, there is django-celery-email which takes care of the rest.

Upvotes: 3

kubus
kubus

Reputation: 783

You can send mails in separate thread, for example:

t = threading.Thread(target=send_mass_email,
            args=[messages],
            kwargs={'fail_silently': True})
t.setDaemon(True)
t.start()

or just use cron and django management commands =) https://docs.djangoproject.com/en/dev/howto/custom-management-commands/

Upvotes: 1

Related Questions