Skip to content

Commit 60dc115

Browse files
committed
AnymailMessage: initialize anymail_status to empty AnymailStatus
Allows clients that use AnymailMessage or AnymailMessageMixin to access (e.g.) message.anymail_status.message_id without an AttributeError, even when using a non-Anymail backend (e.g., during testing). Also clarify docs of anymail_status attribute to note it only gets attached to a normal Django EmailMessage when sent through an Anymail backend. (May help with situation described in #36)
1 parent a1380b8 commit 60dc115

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

anymail/message.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ def __init__(self, *args, **kwargs):
2828
self.template_id = kwargs.pop('template_id', UNSET)
2929
self.merge_data = kwargs.pop('merge_data', UNSET)
3030
self.merge_global_data = kwargs.pop('merge_global_data', UNSET)
31-
self.anymail_status = None
31+
self.anymail_status = AnymailStatus()
3232

3333
# noinspection PyArgumentList
3434
super(AnymailMessageMixin, self).__init__(*args, **kwargs)

docs/sending/anymail_additions.rst

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,19 @@ ESP send status
212212
:class:`~django.core.mail.EmailMessage`, with a normalized version
213213
of the ESP's response.
214214

215+
Anymail backends create this attribute *as they process each message.*
216+
Before that, anymail_status won't be present on an ordinary Django
217+
EmailMessage or EmailMultiAlternatives---you'll get an :exc:`AttributeError`
218+
if you try to access it.
219+
220+
This might cause problems in your test cases, because Django
221+
`substitutes its own locmem email backend`_ during testing (so anymail_status
222+
won't be set even after sending). Your code should either guard against
223+
a missing anymail_status attribute, or use :class:`AnymailMessage`
224+
(or the :class:`AnymailMessageMixin`) which initializes its anymail_status
225+
attribute to a default AnymailStatus object.
226+
227+
After sending through an Anymail backend,
215228
:attr:`~AnymailMessage.anymail_status` will be an object with these attributes:
216229

217230
.. attribute:: message_id
@@ -308,6 +321,10 @@ ESP send status
308321
message.anymail_status.esp_response.json()
309322
310323
324+
.. _substitutes its own locmem email backend:
325+
https://docs.djangoproject.com/en/stable/topics/testing/tools/#email-services
326+
327+
311328
.. _inline-images:
312329

313330
Inline images

0 commit comments

Comments
 (0)