Native ways of testing emails in Python
Let’s start with the native ways of testing Python emails.
Using unit tests and aiosmtpd
Aiosmtpd is a library that lets you set up a local SMTP (Simple Mail Transfer Protocol) server. This will create a testing environment and handle email traffic internally. So, your test emails won’t reach the recipients. Refer to aiosmtpd’s GitHub page for more information.
I’ll create a test for a simple text email.
Prerequisites:
- Python 3.7 and up.
Note: I added the code snippets below in the tests.py file.
To install aiosmtpd, run the pip install aiosmtpd
command.
Run the server with python -m aiosmtpd -n
command.
I’ll use the unit test framework, a standard library in all versions of Python since 2.1, and the smtplib library. smtplib module uses standard RFC 821 protocol for formatting messages.