15

Maybe I don't understand how outbox works but from the documentation I understood that it just catches all outgoing mail during testing.

I created a new project with a new application and added the following code.

from django.test import TestCase
from django.core.mail import send_mail, outbox

class SimpleTest(TestCase):
    def test_basic_addition(self):
        send_mail('Subject here', 
                  'Here is the message.', 
                  'from@example.com', 
                  ['to@example.com'], 
                  fail_silently=False)

        self.assertEqual( len( outbox ), 1 )

When I run python manage.py test app_name it gives an assertion error that 0 != 1. Am I doing something wrong?

Update

Well this is weird if I import django.core.mail and use mail.outbox it does work.

Tried to compare the direct import of outbox and mail.outbox and they both give different results

from django.core import mail
from django.core.mail import send_mail, outbox     
...
self.assertEqual(outbox, mail.outbox)

returns:

- []
+ [<django.core.mail.message.EmailMessage object at 0x1e1fd90>]

Maybe I've been working to long and missing something really obvious?

Pickels
  • 33,902
  • 26
  • 118
  • 178

1 Answers1

21

Maybe I should actually read the documentation.

The outbox attribute is a special attribute that is created only when the locmem e-mail backend is used. It doesn't normally exist as part of the django.core.mail module and you can't import it directly.

https://docs.djangoproject.com/en/dev/topics/testing/tools/#email-services

maxbellec
  • 16,093
  • 10
  • 36
  • 43
Pickels
  • 33,902
  • 26
  • 118
  • 178
  • They should probably make that fail fast for clarity. Thanks for sharing. – Hayden Crocker Apr 20 '16 at 14:14
  • 1
    For other dummies like me that need it spelled out for them: DON'T use `from django.core.mail import outbox`. Instead, use `from django.core import mail` and in your test use `mail.outbox` instead of `outbox`. – ChrisCrossCrash Feb 21 '22 at 17:20