|
3 | 3 | import sendgrid |
4 | 4 | from django.conf import settings |
5 | 5 | from django.core.exceptions import ImproperlyConfigured |
6 | | -from django.core.mail import EmailMultiAlternatives |
7 | 6 | from django.core.mail.backends.base import BaseEmailBackend |
8 | 7 | from email.mime.base import MIMEBase |
9 | 8 | try: |
10 | 9 | import rfc822 |
11 | 10 | except Exception as e: |
12 | 11 | import email.utils as rfc822 |
13 | 12 |
|
| 13 | +from . import exceptions |
| 14 | + |
| 15 | +__all__ = ('HANDLED_CONTENT_TYPES', 'SendGridBackend') |
| 16 | + |
| 17 | +HANDLED_CONTENT_TYPES = {'text/html', 'text/plain'} |
| 18 | + |
14 | 19 |
|
15 | 20 | class SendGridBackend(BaseEmailBackend): |
16 | 21 | """ |
17 | 22 | Email back-end using SendGrid Web API |
18 | 23 | """ |
| 24 | + |
19 | 25 | def __init__(self, fail_silently=False, **kwargs): |
20 | 26 | super(SendGridBackend, self).__init__(fail_silently=fail_silently, **kwargs) |
21 | 27 | self.api_user = getattr(settings, 'SENDGRID_USER', None) |
22 | 28 | self.api_key = getattr(settings, 'SENDGRID_PASSWORD', None) |
| 29 | + self.raise_unhandled = getattr(settings, 'SENDGRID_RAISE_UNHANDLED', False) |
23 | 30 | if self.api_user is None or self.api_key is None: |
24 | 31 | raise ImproperlyConfigured('Either SENDGRID_USER or SENDGRID_PASSWORD was not declared in settings.py') |
25 | 32 | self.sendgrid = sendgrid.SendGridClient(self.api_user, self.api_key, raise_errors=not fail_silently) |
@@ -52,11 +59,18 @@ def _build_sengrid_mail(self, email): |
52 | 59 | mail.set_from(email.from_email) |
53 | 60 |
|
54 | 61 | text, html = '', email.body if email.content_subtype == 'html' else email.body, '' |
55 | | - if not html and isinstance(email, EmailMultiAlternatives): |
56 | | - try: |
57 | | - html = next(c for c, t in email.alternatives if t == 'text/html') |
58 | | - except StopIteration: |
59 | | - pass |
| 62 | + if hasattr(email, 'alternatives'): |
| 63 | + if self.raise_unhandled: |
| 64 | + unhandled_types = [t for c, t in email.alternatives if t not in HANDLED_CONTENT_TYPES] |
| 65 | + if unhandled_types: |
| 66 | + raise exceptions.SendGridUnhandledContentTypeError( |
| 67 | + "SendGrid API don't handle content of type(s) {0}".format(unhandled_types) |
| 68 | + ) |
| 69 | + if not html: |
| 70 | + try: |
| 71 | + html = next(c for c, t in email.alternatives if t == 'text/html') |
| 72 | + except StopIteration: |
| 73 | + pass |
60 | 74 | mail.set_text(text) |
61 | 75 | mail.set_html(html) |
62 | 76 |
|
|
0 commit comments