During the past three months I have developed my first two websites in Python using the Django framework.
Following the tutorial was a great start and it didn’t take me that long to get adapted to Python coming from a PHP background. But when you want to go further the documentation is rather vague and confusing in my opinion.
This week I got to the point where I wanted to test the email functionality. Django offers quite a nice tool while you are developing a website; if you want to see the output of your emails, you can just write them to a file adding a couple of settings.
EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend' EMAIL_FILE_PATH = os.path.join(PROJECT_ROOT, 'tmp')
In addition to this I wanted to check the email configuration before going production, but already using the final parameters for the required settings:
EMAIL_HOST='' EMAIL_HOST_PASSWORD='' EMAIL_HOST_USER='' EMAIL_PORT = 25 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = '' SERVER_EMAIL = ''
The problem is that when Django sets up the testing environment, it changes the email backend to the one in-memory. Fortunately, this behavior can be overridden so you can run a test case with the following code to check if your mail is being actually sent.
from django.test import TestCase from django.core import mail from django.test.utils import override_settings @override_settings(EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend') class EmailTest(TestCase): def test_send_email(self): mail_sent_success = mail.send_mail('Subject here', 'Here is the message.', '', ['firstname.lastname@example.org'], fail_silently=False) self.assertEquals(mail_sent_success, 1)
Notice that DEFAULT_FROM_EMAIL is used if omitting the from_email field.