Celery Error Email: Cannot Receive Celery Emails

I am starting Django and starting celery, I want to set up celery locally. I am currently setting an error message for all failure tasks. What i did is

Add this code to setup.py

CELERY_SEND_TASK_ERROR_EMAILS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
ADMINS = (
    ('test', '...@....com'),
)
EMAIL_HOST='smtp.gmail.com'
EMAIL_HOST_USER='...@gmail.com'
EMAIL_HOST_PASSWORD='...'
EMAIL_PORT=587
EMAIL_USE_TLS = True`

Add this to tasks.py

@app.task(name="test_exception",error_whitelist=[])
+4
source share
3 answers

Solved, I could receive error messages now! I just reorganized the setting.py parameter with the settings in this post.

-1
source

For those trying to do this after version 4.0, it CELERY_SEND_TASK_ERROR_EMAILSwas explicitly deleted ( source ):

. app.mail_admins , .

:

def shared_task_email(func):
    """
    Replacement for @shared_task decorator that emails admins if an exception is raised.
    """
    @wraps(func)
    def new_func(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except:
            subject = "Celery task failure"
            message = traceback.format_exc()
            mail_admins(subject, message)
            raise
    return shared_task(new_func)

@shared_task_email # instead of @shared_task
def test_task():
    raise Exception("Test exception raised by celery test_task")
+2

In settings.py

CELERY_SEND_TASK_ERROR_EMAILS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
ADMINS = (
    ('test', '...@....com'),  # Admins syntax may vary by django version
)
EMAIL_HOST='smtp.gmail.com'
EMAIL_HOST_USER='...@gmail.com'
EMAIL_HOST_PASSWORD='...'
EMAIL_PORT=587
EMAIL_USE_TLS = True

Then in the celery.py file, if you create the configuration, use this:

app.conf.update(
    ADMINS = ('test', '...@....com'),
    CELERY_SEND_TASK_ERROR_EMAILS= True,
    ....
    ....
    )

To test this code, check the use of these lines in the shell:

from app_name.celery import app
app.mail_admins('Subject', 'body', fail_silently=False)

This is necessary to send email to your admins. If this work, then it will certainly send a letter on the failed task.

0
source

Source: https://habr.com/ru/post/1608076/


All Articles