# -*- coding: utf-8 -*-
import json
from base64 import b64encode, b64decode
from datetime import datetime
from decimal import Decimal
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
import six
from django.core import mail
from django.test import SimpleTestCase
from django.test.utils import override_settings
from django.utils.timezone import get_fixed_timezone, override as override_current_timezone
from anymail.exceptions import (AnymailAPIError, AnymailConfigurationError, AnymailSerializationError,
AnymailUnsupportedFeature)
from anymail.message import attach_inline_image_file
from .mock_requests_backend import RequestsBackendMockAPITestCase, SessionSharingTestCasesMixin
from .utils import sample_image_content, sample_image_path, SAMPLE_IMAGE_FILENAME, AnymailTestMixin
# noinspection PyUnresolvedReferences
longtype = int if six.PY3 else long # NOQA: F821
@override_settings(EMAIL_BACKEND='anymail.backends.sendinblue.EmailBackend',
ANYMAIL={'SENDINBLUE_API_KEY': 'test_api_key'})
class SendinBlueBackendMockAPITestCase(RequestsBackendMockAPITestCase):
# SendinBlue v3 success responses are empty
DEFAULT_RAW_RESPONSE = b'{"messageId":"<201801020304.1234567890@smtp-relay.mailin.fr>"}'
DEFAULT_STATUS_CODE = 201 # SendinBlue v3 uses '201 Created' for success (in most cases)
def setUp(self):
super(SendinBlueBackendMockAPITestCase, self).setUp()
# Simple message useful for many tests
self.message = mail.EmailMultiAlternatives('Subject', 'Text Body', 'from@example.com', ['to@example.com'])
class SendinBlueBackendStandardEmailTests(SendinBlueBackendMockAPITestCase):
"""Test backend support for Django standard email features"""
def test_send_mail(self):
"""Test basic API for simple send"""
mail.send_mail('Subject here', 'Here is the message.',
'from@sender.example.com', ['to@example.com'], fail_silently=False)
self.assert_esp_called('https://api.sendinblue.com/v3/smtp/email')
http_headers = self.get_api_call_headers()
self.assertEqual(http_headers["api-key"], "test_api_key")
self.assertEqual(http_headers["Content-Type"], "application/json")
data = self.get_api_call_json()
self.assertEqual(data['subject'], "Subject here")
self.assertEqual(data['textContent'], "Here is the message.")
self.assertEqual(data['sender'], {'email': "from@sender.example.com"})
self.assertEqual(data['to'], [{'email': "to@example.com"}])
def test_name_addr(self):
"""Make sure RFC2822 name-addr format (with display-name) is allowed
(Test both sender and recipient addresses)
"""
msg = mail.EmailMessage(
'Subject', 'Message', 'From Name This is an important message. This is an important message.
\u2019
') def test_embedded_images(self): # SendinBlue doesn't support inline image # inline image are just added as a content attachment image_filename = SAMPLE_IMAGE_FILENAME image_path = sample_image_path(image_filename) cid = attach_inline_image_file(self.message, image_path) # Read from a png file html_content = 'This has an image.
First html is OK
", "text/html") self.message.attach_alternative("And maybe second html, too
", "text/html") with self.assertRaises(AnymailUnsupportedFeature): self.message.send() def test_non_html_alternative(self): self.message.body = "Text body" self.message.attach_alternative("{'maybe': 'allowed'}", "application/json") with self.assertRaises(AnymailUnsupportedFeature): self.message.send() def test_api_failure(self): self.set_mock_response(status_code=400) with self.assertRaisesMessage(AnymailAPIError, "SendinBlue API response 400"): mail.send_mail('Subject', 'Body', 'from@example.com', ['to@example.com']) # Make sure fail_silently is respected self.set_mock_response(status_code=400) sent = mail.send_mail('Subject', 'Body', 'from@example.com', ['to@example.com'], fail_silently=True) self.assertEqual(sent, 0) def test_api_error_includes_details(self): """AnymailAPIError should include ESP's error message""" # JSON error response: error_response = b"""{ "code": "invalid_parameter", "message": "valid sender email required" }""" self.set_mock_response(status_code=400, raw=error_response) with self.assertRaises(AnymailAPIError) as cm: self.message.send() err = cm.exception self.assertIn("code", str(err)) self.assertIn("message", str(err)) # No content in the error response: self.set_mock_response(status_code=502, raw=None) with self.assertRaises(AnymailAPIError): self.message.send() class SendinBlueBackendAnymailFeatureTests(SendinBlueBackendMockAPITestCase): """Test backend support for Anymail added features""" def test_envelope_sender(self): # SendinBlue does not have a way to change envelope sender. self.message.envelope_sender = "anything@bounces.example.com" with self.assertRaisesMessage(AnymailUnsupportedFeature, 'envelope_sender'): self.message.send() def test_metadata(self): self.message.metadata = {'user_id': "12345", 'items': 6, 'float': 98.6, 'long': longtype(123)} self.message.send() data = self.get_api_call_json() metadata = json.loads(data['headers']['X-Mailin-custom']) self.assertEqual(metadata['user_id'], "12345") self.assertEqual(metadata['items'], 6) self.assertEqual(metadata['float'], 98.6) self.assertEqual(metadata['long'], longtype(123)) def test_send_at(self): utc_plus_6 = get_fixed_timezone(6 * 60) utc_minus_8 = get_fixed_timezone(-8 * 60) with override_current_timezone(utc_plus_6): # Timezone-aware datetime converted to UTC: self.message.send_at = datetime(2016, 3, 4, 5, 6, 7, tzinfo=utc_minus_8) with self.assertRaises(AnymailUnsupportedFeature): self.message.send() def test_tag(self): self.message.tags = ["receipt"] self.message.send() data = self.get_api_call_json() self.assertCountEqual(data['headers']["X-Mailin-tag"], "receipt") def test_multiple_tags(self): self.message.tags = ["receipt", "repeat-user"] with self.assertRaises(AnymailUnsupportedFeature): self.message.send() def test_tracking(self): # Test one way... self.message.track_clicks = False self.message.track_opens = True with self.assertRaises(AnymailUnsupportedFeature): self.message.send() # ...and the opposite way self.message.track_clicks = True self.message.track_opens = False with self.assertRaises(AnymailUnsupportedFeature): self.message.send() def test_template_id(self): # subject, body, and from_email must be None for SendinBlue template send: message = mail.EmailMessage( subject=None, body=None, # recipient and reply_to display names are not allowed to=['alice@example.com'], # single 'to' recommended (all 'to' get the same message) cc=['cc1@example.com', 'cc2@example.com'], bcc=['bcc@example.com'], reply_to=['reply@example.com'], ) message.from_email = None # from_email must be cleared after constructing EmailMessage message.template_id = 12 # SendinBlue uses per-account numeric ID to identify templates message.merge_global_data = { 'buttonUrl': 'https://example.com', } message.send() # Template API call uses different endpoint and payload format from normal send: self.assert_esp_called('/v3/smtp/templates/12/send') data = self.get_api_call_json() self.assertEqual(data['emailTo'], ["alice@example.com"]) self.assertEqual(data['emailCc'], ["cc1@example.com", "cc2@example.com"]) self.assertEqual(data['emailBcc'], ["bcc@example.com"]) self.assertEqual(data['replyTo'], 'reply@example.com') self.assertEqual(data['attributes'], {'buttonUrl': 'https://example.com'}) # Make sure these normal-send parameters didn't get left in: self.assertNotIn('to', data) self.assertNotIn('cc', data) self.assertNotIn('bcc', data) self.assertNotIn('sender', data) self.assertNotIn('subject', data) self.assertNotIn('textContent', data) self.assertNotIn('htmlContent', data) def test_unsupported_template_overrides(self): # SendinBlue doesn't allow overriding any template headers/content message = mail.EmailMessage(to=['to@example.com']) message.template_id = "9" message.from_email = "from@example.com" with self.assertRaisesMessage(AnymailUnsupportedFeature, "overriding template from_email"): message.send() message.from_email = None message.subject = "nope, can't change template subject" with self.assertRaisesMessage(AnymailUnsupportedFeature, "overriding template subject"): message.send() message.subject = None message.body = "nope, can't change text body" with self.assertRaisesMessage(AnymailUnsupportedFeature, "overriding template body content"): message.send() message.content_subtype = "html" with self.assertRaisesMessage(AnymailUnsupportedFeature, "overriding template body content"): message.send() message.body = None def test_unsupported_template_display_names(self): # SendinBlue doesn't support display names in template recipients or reply-to message = mail.EmailMessage() message.from_email = None message.template_id = "9" message.to = ["Recipient