A Django email backend that uses a celery task for sending the email.

Overview

django-celery-email - A Celery-backed Django Email Backend

A Django email backend that uses a Celery queue for out-of-band sending of the messages.

Warning

This version requires the following versions:

  • Python >= 3.5
  • Django 2.2, and 3.0
  • Celery 4.0

Using django-celery-email

To enable django-celery-email for your project you need to add djcelery_email to INSTALLED_APPS:

INSTALLED_APPS += ("djcelery_email",)

You must then set django-celery-email as your EMAIL_BACKEND:

EMAIL_BACKEND = 'djcelery_email.backends.CeleryEmailBackend'

By default django-celery-email will use Django's builtin SMTP email backend for the actual sending of the mail. If you'd like to use another backend, you may set it in CELERY_EMAIL_BACKEND just like you would normally have set EMAIL_BACKEND before you were using Celery. In fact, the normal installation procedure will most likely be to get your email working using only Django, then change EMAIL_BACKEND to CELERY_EMAIL_BACKEND, and then add the new EMAIL_BACKEND setting from above.

Mass email are sent in chunks of size CELERY_EMAIL_CHUNK_SIZE (defaults to 10).

If you need to set any of the settings (attributes) you'd normally be able to set on a Celery Task class had you written it yourself, you may specify them in a dict in the CELERY_EMAIL_TASK_CONFIG setting:

CELERY_EMAIL_TASK_CONFIG = {
    'queue' : 'email',
    'rate_limit' : '50/m',  # * CELERY_EMAIL_CHUNK_SIZE (default: 10)
    ...
}

There are some default settings. Unless you specify otherwise, the equivalent of the following settings will apply:

CELERY_EMAIL_TASK_CONFIG = {
    'name': 'djcelery_email_send',
    'ignore_result': True,
}

After this setup is complete, and you have a working Celery install, sending email will work exactly like it did before, except that the sending will be handled by your Celery workers:

from django.core import mail

emails = (
    ('Hey Man', "I'm The Dude! So that's what you call me.", '[email protected]', ['[email protected]']),
    ('Dammit Walter', "Let's go bowlin'.", '[email protected]', ['[email protected]']),
)
results = mail.send_mass_mail(emails)

results will be a list of celery AsyncResult objects that you may ignore, or use to check the status of the email delivery task, or even wait for it to complete if want. You have to enable a result backend and set ignore_result to False in CELERY_EMAIL_TASK_CONFIG if you want to use these. You should also set CELERY_EMAIL_CHUNK_SIZE = 1 in settings if you are concerned about task status and results.

See the Celery docs for more info.

len(results) will be the number of emails you attempted to send divided by CELERY_EMAIL_CHUNK_SIZE, and is in no way a reflection on the success or failure of their delivery.

Changelog

3.0.0 - 2019.12.10

  • Support for Django 3.0
  • Support for Python 3.8
  • Droppped support for Django 1.x, Django 2.0 and Django 2.1
  • Droppped support for Python 2.7

2.0.2 - 2019.05.29

  • Reduce memory usage by running email_to_dict on chunks. Thanks Paul Brown.
  • Simplify dict_to_email for readability and efficiency. Thanks Paul Brown.
  • Update test matrix for supported versions of Django, Celery and Python. Thanks James.

2.0.1 - 2018.18.27

  • Fix bug preventing sending text/* encoded mime attachments. Thanks Cesar Canassa.

2.0 - 2017.07.10

  • Support for Django 1.11 and Celery 4.0
  • Dropped support for Celery 2.x and 3.x
  • Dropped support for Python 3.3

1.1.5 - 2016.07.20

  • Support extra email attributes via CELERY_EMAIL_MESSAGE_EXTRA_ATTRIBUTES setting
  • Updated version requirements in README

1.1.4 - 2016.01.19

  • Support sending email with embedded images. Thanks Georg Zimmer.
  • Document CELERY_EMAIL_CHUNK_SIZE. Thanks Jonas Haag.
  • Add exception handling to email backend connection. Thanks Tom.

1.1.3 - 2015.11.06

  • Support setting celery.base from string. Thanks Matthew Jacobi.
  • Use six for py2/3 string compatibility. Thanks Matthew Jacobi.
  • Pass content_subtype back in for retries. Thanks Mark Joshua Tan.
  • Rework how tests work, add tox, rework travis-ci matrix.
  • Use six from django.utils.
  • Release a universal wheel.

1.1.2 - 2015.07.06

  • Fix for HTML-only emails. Thanks gnarvaja.

1.1.1 - 2015.03.20

  • Fix for backward compatibility of task kwarg handling - Thanks Jeremy Thurgood.

1.1.0 - 2015.03.06

  • New PyPI release rolling up 1.0.5 changes and some cleanup.
  • More backward compatability in task. Will still accept message objects and lists of message objects.
  • Thanks again to everyone who contributed to 1.0.5.

1.0.5 - 2014.08.24

  • Django 1.6 support, Travis CI testing, chunked sending & more - thanks Jonas Haag.
  • HTML email support - thanks Andres Riancho.
  • Support for JSON transit for Celery, sponsored by DigiACTive.
  • Drop support for Django 1.2.

1.0.4 - 2013.10.12

  • Add Django 1.5.2 and Python 3 support.
  • Thanks to Stefan Wehrmeyer for the contribution.

1.0.3 - 2012.03.06

  • Backend will now pass any kwargs with which it is initialized to the email sending backend.
  • Thanks to Fedor Tyurin for the contribution.

1.0.2 - 2012.02.21

  • Task and backend now accept kwargs that can be used in signal handlers.
  • Task now returns the result from the email sending backend.
  • Thanks to Yehonatan Daniv for these changes.

1.0.1 - 2011.10.06

  • Fixed a bug that resulted in tasks that were throwing errors reporting success.
  • If there is an exception thrown by the sending email backend, the result of the task will now be this exception.
Comments
  • Support for Django 3.x

    Support for Django 3.x

    This change is a breaking change because it removes support for Python 2.x so a major release would be necessary.

    The Django team suggests to drop support of Django versions prior to 2.2 in their release notes.

    opened by philippbosch 12
  • Add exception handling to celery backend connection

    Add exception handling to celery backend connection

    This will allow celery email to be fault tolerant to connection issues with the celery email backend.

    Catching a connection issues allows celery to retry failed tasks. If the connection error is not caught an exception will be raised before the retry logic.

    opened by tomleo 8
  • Extra args on EmailMessage no longer working

    Extra args on EmailMessage no longer working

    I have my configuration set up like this

    EMAIL_BACKEND = 'djcelery_email.backends.CeleryEmailBackend'
    CELERY_EMAIL_BACKEND = "djrill.mail.backends.djrill.DjrillBackend"
    

    meaning that I use Mandrill to send mails.

    In 1.0.4 I was able to set extra args on the EmailMessage object to use templates in Mandrill

    email.template_name = 'report-{}'.format(get_language())
    email.template_content = {}
    email.global_merge_vars = {
        'CLIENT': Client.objects.get(slug=client_slug).name,
    }
    

    All versions after 1.0.4 no longer sends these arguments all the way to Mandrill

    opened by chripede 8
  • Support Celery's JSON serializer

    Support Celery's JSON serializer

    This supports the use of Celery's JSON serializer, which improves the security of Celery.

    Prior to this patch, attempting to use Celery with the JSON serialization (as opposed to pickling) generated error messages complaining that a django.core.mail.EmailMessage is not JSON serializable. This patch converts email messages to dictionaries which are JSON serializable.

    For those still using the pickle serializer, everything should continue to work the same.

    Caveat on JSON-serializing attachments

    This patch copies the attachments property of EmailMessages without further processing. Per [https://docs.djangoproject.com/en/dev/topics/email/#emailmessage-objects](the Django docs on EmailMessage objects), attachments are:

    either email.MIMEBase.MIMEBase instances, or (filename, content, mimetype) triples.

    As I understand it, this means that attachments as MIMEBase instances will still fail, but the triples may succeed. My application doesn't send attachments at the moment, so I haven't tested this. If in the deep distant future I get the opportunity to test it I will extend the patch.

    Attachments will still work for those using pickling. In the mean time, this patch still enhances support for those using JSON - instead of everything failing, only a limited subset of things fail.

    opened by daxtens 7
  • Import under Django 3.0 fails

    Import under Django 3.0 fails

    opened by peterthomassen 5
  • django-celery shouldn't be a dependency for this app

    django-celery shouldn't be a dependency for this app

    Replacing django-celery dependency with celery as it django-celery is no longer the preferred way to integrate celery into a django project -> https://celery.readthedocs.org/en/master/django/first-steps-with-django.html#using-celery-with-django

    opened by teosibileau 5
  • Django 1.6 support, Travis, message chunking

    Django 1.6 support, Travis, message chunking

    This fixes the use of the deprecated execute_manager (not available in Django 1.3 and 1.6+).

    It also adds support for Travis -- if you haven't heard of Travis, check out http://about.travis-ci.org/docs/

    You can then add this cool build badge to your README file: Build Status

    The latest commit also adds chunking and refactors the tests.

    I'm sorry that the patch is so large, but it's all documented well and fully tested.

    Tested on (see Travis): Django 1.2 to 1.6, Celery 2.3 to 3.1, Python 2.6 to 3.3 + PyPy

    opened by jonashaag 5
  • SMTPServerDisconnected('please run connect() first',)

    SMTPServerDisconnected('please run connect() first',)

    I am getting SMTPServerDisconnected('please run connect() first',) on some SMTP servers. I have no clue what could be wrong. For example GMail is working fine. When I move to my local provider I get this error. Do you think it could be a problem of django-celery-email?

    Funny thing is, when I ommit EMAIL_TIMEOUT setting, those e-mails are sent in about 270 seconds or more! One by one ...

    opened by adi- 4
  • HTML only emails sent as plain text

    HTML only emails sent as plain text

    Messages with content_subtype overridden to "html" are sent as plain text when passing through djcelery.

    It's because in the serialization process (email_to_dict function), only some attributes are copied.

    Fix in https://github.com/pmclanahan/django-celery-email/pull/17

    opened by gnarvaja 4
  • rate_limit task setting will discard tasks if exceeded

    rate_limit task setting will discard tasks if exceeded

    I know it's not a required setting, but it appears as though celery will just discard the tasks if this rate_limit is exceeded. In other words, if this is set, and you're exceeded the rate_limit sending emails, the emails will just get discarded which is probably not the behavior you intended.

    Please correct me if I'm wrong.

    opened by kimsterv 4
  • Fix attachments with a

    Fix attachments with a "text/*" mimetype failing to be decoded.

    For emails attachments contains a mimetype starting with text/, Django expects the content to be a string. This behavior is documented in here:

    https://docs.djangoproject.com/en/2.0/topics/email/#emailmessage-objects

    This causes both the email_to_dict and dict_to_email function to fail. email_to_dict fails because the attachment returned by Django is a string and not bytes, and dict_to_email fails because Django itself complains if you try to send an email with a text/* mimetype and a binary content.

    This causes the a bytes-like object is required, not 'str' error to be raised at this line

    I added workarounds to both functions and a regression test.

    opened by canassa 3
  • Migrate CI to GitHub actions

    Migrate CI to GitHub actions

    The pipelines on travis aren't operational

    refer: https://travis-ci.org/github/pmclanahan/django-celery-email

    Created Github actions workflows as replacement

    • created workflow for running flake8
    • created workflow for running tox
    • removed flake8 from tox
    • restrict workflows to run on push/pull-request to master or main branches only

    TODO: remove travis update build-passing badge on readme

    opened by dheerajreal 0
  • Celery task fails with 'too many concurrent connections'

    Celery task fails with 'too many concurrent connections'

    When sending a lot of mails with django-celery-email as backend, I often get an error in my celery logs, that there were too many concurrent connections.

    I have set EMAIL_BACKEND accordingly:

    EMAIL_BACKEND = 'djcelery_email.backends.CeleryEmailBackend'
    

    And I am sending emails like so:

    with mail.get_connection() as connection:
        for recipient in set(recipients):
            email = EmailMessage(subject, content, sender, [recipient],
                                 headers=headers,
                                 connection=connection, **kwargs)
            if attachments is not None:
                for attach in attachments:
                    email.attach_file(attach)
            try:
                email.send(fail_silently=True)
            except Exception as e:
                print("Error when sending mail:", e)
                failed = True
            else:
                succeeded = True
    

    I was expecting that this opens one connection and sends all emails using this one connection. Is this a wrong assumption? How can I force the mail backend to only use one single connection?

    opened by erichhasl 0
  • Type error for send_messages

    Type error for send_messages

    Hello,

    I'm using 2.0.0 version on my project. I have a some problems. I found this in my log file.

    "Cannot reach CELERY_EMAIL_BACKEND django.core.mail.backends.smtp.EmailBackend"

    And After, we add this parameter.

    CELERY_EMAIL_BACKEND = 'djcelery_email.backends.CeleryEmailBackend'

    After, I have a new problem.

    djcelery_email_send_multiple[49d3b5a9-b1af-424c-8709-95b506d66c49]: Failed to send email message to [u'[email protected]'], retrying. (TypeError("unsupported operand type(s) for +=: 'int' and 'list'",))

    Because send_messages method of CeleryEmailBackend return to list.

    https://github.com/pmclanahan/django-celery-email/blob/be1a5bb056d8acf10d33703c587c02850afd29ff/djcelery_email/tasks.py#L50

    opened by mkaykisiz 5
  • Compatibility with Django v5.0

    Compatibility with Django v5.0

    Hi,

    Has anybody been able to get django-celery-email working with celery 5? I have tried to get it running but get an error and not sure of it should work out of the box or there is some compatibility issue.

    Thanks

    opened by kowsari 3
  • Extend support of actual versions of Django and Python

    Extend support of actual versions of Django and Python

    Hi @pmclanahan , Thank you for such useful library.

    That PR adds support for latest actual version of Python and Django. Helpful links:

    • https://docs.djangoproject.com/en/3.2/releases/3.1/
    • https://docs.djangoproject.com/en/3.2/releases/3.2/
    opened by DmytroLitvinov 1
Owner
Paul McLanahan
Backend Webdev @mozilla. I also go by @pmac for most of my coding tasks.
Paul McLanahan
A Django email backend for Amazon's Simple Email Service

Django-SES Info: A Django email backend for Amazon's Simple Email Service Author: Harry Marr (http://github.com/hmarr, http://twitter.com/harrymarr) C

null 882 Dec 29, 2022
Djrill is an email backend and new message class for Django users that want to take advantage of the Mandrill transactional email service from MailChimp.

Djrill: Mandrill Transactional Email for Django Djrill integrates the Mandrill transactional email service into Django. PROJECT STATUS: INACTIVE As of

Brack3t 327 Oct 1, 2022
GMailBomber is a form of Internet abuse which is perpetrated through the sending of massive volumes of email to a specific email address with the goal of overflowing the mailbox and overwhelming the mail server hosting the address, making it into some form of denial of service attack.

GMailBomber is a form of Internet abuse which is perpetrated through the sending of massive volumes of email to a specific email address with the goal of overflowing the mailbox and overwhelming the mail server hosting the address, making it into some form of denial of service attack.

Muneeb 5 Nov 13, 2022
A Django app that allows you to send email asynchronously in Django. Supports HTML email, database backed templates and logging.

Django Post Office Django Post Office is a simple app to send and manage your emails in Django. Some awesome features are: Allows you to send email as

User Inspired 856 Dec 25, 2022
A package for sending email from your Pyramid application

pyramid_mailer pyramid_mailer is a package for sending email from your Pyramid application. It is compatible with Python 2.7, 3.4, 3.5, 3.6, and 3.7 a

Pylons Project 50 Sep 17, 2022
Bulk Email and certificate sending application

demir.ai E-mail services This application allows you to send automatic mass mail and automatic mass certificates to the people in your mailing list, m

Ahmet Furkan DEMIR 16 Nov 1, 2022
Fast Anonymous Email Sending Tool

Email-Fake Fast Anonymous Email Sending Tool ?? Github Statistics : Termux For Install: pkg install python pkg install python2 git clone https://githu

Aryan 7 May 28, 2022
Command line interface for sending email using SMTP (ships with Gmail configuration).

mailsend Description Lightweight command line interface for sending email using SMTP. Default configuration is set for Gmail (smtp.gmail.com at port 5

Keith Mathe 1 Mar 22, 2022
Automated email sending application.

autoMail Automated email sending application. This application sends email to a user when added to database. Email message contains the temperature of

Bhat Owais 1 Feb 12, 2022
An email sending system with random confirmation code.

email_sending An email sending system with random confirmation code. Description Confirmation emails are sent based on the list of email addresses. Ea

Larissa Queiroz 2 Mar 22, 2022
Mailer is python3 script use for sending spear-phishing to target email...It was created by Spider Anongreyhat

Mailer Mailer is a python3 script. It's used for sending spear-phishing to target email...It was created by Spider Anongreyhat Screenshots Installatio

Spider Anongreyhat 31 Dec 5, 2022
Esio_dev 3 Oct 15, 2021
faceFarm is an active yahoo email detection script that functions to take over the facebook account using email.

faceFarm – The simple Email Detector. Email Valid Detector for Facebook (Yahoo) faceFarm is an active yahoo email detection script that functions to t

Fadjrir Herlambang 2 Jan 18, 2022
This Python program generates a random email address and password from a 2 big lists and checks the generated email.

This Python program generates a random email address and password from a 2 big lists and checks the generated email.

Killin 13 Dec 4, 2022
Email-osint - Email OSINT tool written in python3

Email-osint - Email OSINT tool written in python3

Surtains 7 Nov 28, 2022
Django module to easily send emails/sms/tts/push using django templates stored on database and managed through the Django Admin

Django-Db-Mailer Documentation available at Read the Docs. What's that Django module to easily send emails/push/sms/tts using django templates stored

LPgenerator 250 Dec 21, 2022
Fastapi mail system sending mails(individual, bulk) attachments(individual, bulk)

Fastapi-mail The fastapi-mail simple lightweight mail system, sending emails and attachments(individual && bulk) ?? Installation $ pip install fastap

Sabuhi 399 Dec 29, 2022
Python library for sending emails.

Mail.py Python library for sending emails. Installation git clone https://github.com/SunPodder/Mail.py cd Mail.py python setup.py install Usage Imp

Sun 3 Oct 15, 2021
This Tool Is For Sending Emails From A Terminal(Termux/Kali) etc.

This is a Basic python script to send emails from a Terminal(Termux/Kali) are the only tested currently.

AnonyVox 2 Apr 4, 2022