Debian Codegraph @

djcelery_email/tasks.py

raw
1 from django.conf import settings
2 from django.core.mail import EmailMessage, get_connection
3
4 from celery import shared_task
5
6 # Make sure our AppConf is loaded properly.
7 import djcelery_email.conf # noqa
8 from djcelery_email.utils import dict_to_email, email_to_dict
9
10 # Messages *must* be dicts, not instances of the EmailMessage class
11 # This is because we expect Celery to use JSON encoding, and we want to prevent
12 # code assuming otherwise.
13
14 TASK_CONFIG = {'name': 'djcelery_email_send_multiple', 'ignore_result': True}
15 TASK_CONFIG.update(settings.CELERY_EMAIL_TASK_CONFIG)
16
17 # import base if string to allow a base celery task
18 if 'base' in TASK_CONFIG and isinstance(TASK_CONFIG['base'], str):
19 from django.utils.module_loading import import_string
20 TASK_CONFIG['base'] = import_string(TASK_CONFIG['base'])
21
22
23 @shared_task(**TASK_CONFIG)
24 def send_emails(messages, backend_kwargs=None, **kwargs):
25 # backward compat: handle **kwargs and missing backend_kwargs
26 combined_kwargs = {}
27 if backend_kwargs is not None:
28 combined_kwargs.update(backend_kwargs)
29 combined_kwargs.update(kwargs)
30
31 # backward compat: catch single object or dict
32 if isinstance(messages, (EmailMessage, dict)):
33 messages = [messages]
34
35 # make sure they're all dicts
36 messages = [email_to_dict(m) for m in messages]
37
38 conn = get_connection(backend=settings.CELERY_EMAIL_BACKEND, **combined_kwargs)
39 try:
40 conn.open()
41 except Exception:
42 logger.exception("Cannot reach CELERY_EMAIL_BACKEND %s", settings.CELERY_EMAIL_BACKEND)
43
44 messages_sent = 0
45
46 for message in messages:
47 try:
48 sent = conn.send_messages([dict_to_email(message)])
49 if sent is not None:
50 messages_sent += sent
51 logger.debug("Successfully sent email message to %r.", message['to'])
52 except Exception as e:
53 # Not expecting any specific kind of exception here because it
54 # could be any number of things, depending on the backend
55 logger.warning("Failed to send email message to %r, retrying. (%r)",
56 message['to'], e)
57 send_emails.retry([[message], combined_kwargs], exc=e, throw=False)
58
59 conn.close()
60 return messages_sent
61
62
63 # backwards compatibility
64 SendEmailTask = send_email = send_emails
65
66
67 try:
68 from celery.utils.log import get_task_logger
69 logger = get_task_logger(__name__)
70 except ImportError:
71 logger = send_emails.get_logger()