PyTest email testing is a framework used for testing email functionality
Send and receive test emails in Python using MailSlurp, with step-by-step instructions for creating accounts, sending and receiving emails.
Send and receive emails in Python from MailSlurp test email accounts.
Add dependencies
To use test email accounts in PyTests first sign up for a free MailSlurp account.
Then install the MailSlurp python library and PyTest with pip:
pip install mailslurp-client pytest
Or add them to your requirements.txt:
mailslurp-client==7.0.9
pytest==4.3.1
Configure email client
Next add the MailSlurp client and configure it with your MailSlurp API Key.
import mailslurp_client
configuration = mailslurp_client.Configuration()
configuration.api_key['x-api-key'] = 'YOUR_MAILSLURP_API_KEY'
Common usage
Create test email accounts
We can use MailSlurp to create test inboxes. These have real email addresses.
def test_can_create_email_address():
with mailslurp_client.ApiClient(configuration) as api_client:
# create an inbox using the inbox controller
api_instance = mailslurp_client.InboxControllerApi(api_client)
inbox = api_instance.create_inbox()
# check the id and email_address of the inbox
assert len(inbox.id) > 0
assert "mailslurp.com" in inbox.email_address
Send emails
You can send emails in Python using MailSlurp too:
def test_can_send_email():
with mailslurp_client.ApiClient(configuration) as api_client:
# first create an inbox
api_instance = mailslurp_client.InboxControllerApi(api_client)
inbox = api_instance.create_inbox()
# send email from the inbox
send_email_options = mailslurp_client.SendEmailOptions()
send_email_options.to = [inbox.email_address]
send_email_options.subject = "Hello"
send_email_options.body = """
<h1>MailSlurp supports HTML</h1>
"""
send_email_options.is_html = True
api_instance.send_email(inbox.id, send_email_options=send_email_options)
Receive emails and extract contents
To receive emails in PyTest use MailSlurp's waitFor controllers to receive emails directly in code. This test demonstrates how to send an email then receive its content. In this way we can read emails in Python tests.
def test_can_receive_emails_and_extract_content():
with mailslurp_client.ApiClient(configuration) as api_client:
# create two inboxes for testing
inbox_controller = mailslurp_client.InboxControllerApi(api_client)
inbox_1 = inbox_controller.create_inbox()
inbox_2 = inbox_controller.create_inbox()
# send email from inbox 1 to inbox 2
send_email_options = mailslurp_client.SendEmailOptions()
send_email_options.to = [inbox_2.email_address]
send_email_options.subject = "Hello inbox 2"
send_email_options.body = "Your code is: 123"
inbox_controller.send_email(inbox_1.id, send_email_options=send_email_options)
# receive email for inbox 2
waitfor_controller = mailslurp_client.WaitForControllerApi(api_client)
email = waitfor_controller.wait_for_latest_email(inbox_id=inbox_2.id, timeout=30000, unread_only=True)
assert email.subject == "Hello inbox 2"
# extract content from body
pattern = re.compile('Your code is: ([0-9]{3})')
matches = pattern.match(email.body)
code = matches.group(1)
assert code == "123"
Test sign-up verification and login codes
The examples above send a message between two MailSlurp inboxes. In a real test suite the email comes from your own application: signing up sends a verification link, or a passwordless login emails a one-time code. Each test needs its own address, so parallel runs never read each other's messages, and a way to wait for the email instead of sleeping for a fixed time.
Create an inbox for each test
Put the client and an inbox fixture in conftest.py. Every test that asks for inbox gets a new email address, and the inbox is deleted when the test finishes.
import os
import mailslurp_client
import pytest
@pytest.fixture(scope="session")
def mailslurp():
configuration = mailslurp_client.Configuration()
configuration.api_key["x-api-key"] = os.environ["MAILSLURP_API_KEY"]
with mailslurp_client.ApiClient(configuration) as api_client:
yield api_client
@pytest.fixture
def inbox(mailslurp):
inboxes = mailslurp_client.InboxControllerApi(mailslurp)
inbox = inboxes.create_inbox_with_defaults()
yield inbox
inboxes.delete_inbox(inbox.id)
Set MAILSLURP_API_KEY as an environment variable or a CI secret rather than writing the key into the code.
Verify a new account from the email link
Sign up with the inbox address, wait for the verification email, then open the link. get_email_links returns every link in the message, so you can pick out the verification URL without parsing the HTML yourself. The requests calls stand in for however your tests already talk to your app, such as an API client or a Playwright page.
import os
import re
import mailslurp_client
import requests
APP_URL = os.environ["APP_URL"]
def test_new_account_is_verified_by_email(mailslurp, inbox):
requests.post(f"{APP_URL}/api/sign-up", json={"email": inbox.email_address, "password": "Test-password-123"})
email = mailslurp_client.WaitForControllerApi(mailslurp).wait_for_latest_email(
inbox_id=inbox.id, timeout=60000, unread_only=True
)
assert "verify" in email.subject.lower()
links = mailslurp_client.EmailControllerApi(mailslurp).get_email_links(email.id).links
verify_link = next(link for link in links if "/verify" in link)
assert requests.get(verify_link).status_code == 200
wait_for_latest_email returns as soon as the email arrives. If nothing arrives within 60 seconds it raises an error, so a missing email fails the test with a clear cause.
Log in with a code from the email
For passwordless or two-step login, read the code from the email body and submit it. Add this test to the same file:
def test_user_logs_in_with_emailed_code(mailslurp, inbox):
requests.post(f"{APP_URL}/api/login-code", json={"email": inbox.email_address})
email = mailslurp_client.WaitForControllerApi(mailslurp).wait_for_latest_email(
inbox_id=inbox.id, timeout=60000, unread_only=True
)
code = re.search(r"\b(\d{6})\b", email.body).group(1)
response = requests.post(f"{APP_URL}/api/login", json={"email": inbox.email_address, "code": code})
assert response.status_code == 200
Change the pattern if your codes aren't six digits. These examples use mailslurp-client 17.6. To test codes sent by text message as well, see pytest email and SMS testing.
Next steps
MailSlurp is free for personal use. So check out www.mailslurp.com for more.