Create real email addresses on demand. Send and receive emails and attachments from code and tests using Python.
MailSlurp is an email API service that lets you create real email addresses in code. You can then send and receive emails and attachments in Python applications and tests.
First you'll need an API Key. Create a free account and copy the key from your dashboard.
Install package
MailSlurp has an official PyPI package called mailslurp-client. It supports Python version 2 and 3.
pip install mailslurp-client
On some systems you may need to install distutils. If you encounter a CERTIFICATE_VERIFY_VALID error you can install certifi and certifi-win32 for Windows:
pip install python-certifi-win32
Configure
Once installed you can import mailslurp_client and create a configuration with your API Key.
# configure smtp client using access details
from smtplib import SMTP
with SMTP(
host=smtp_access.secure_smtp_server_host,
port=smtp_access.secure_smtp_server_port,
) as smtp:
msg = "Subject: Test subject
This is the body"
smtp.login(
user=smtp_access.secure_smtp_username,
password=smtp_access.secure_smtp_password,
)
smtp.sendmail(
from_addr=inbox.email_address,
to_addrs=[inbox.email_address],
msg=msg,
)
smtp.quit()
inbox = inbox_controller.get_inbox(inbox_id=inbox.id)
self.assertTrue("@mailslurp" in inbox.email_address)
# get by email address
inbox_by_email = inbox_controller.get_inbox_by_email_address(
inbox.email_address
)
self.assertTrue(inbox_by_email.exists)
# get by name
inbox_by_name = inbox_controller.get_inbox_by_name(inbox.name)
self.assertTrue(inbox_by_name.exists)
Delete an inbox
inbox_controller.delete_inbox(inbox_id=inbox.id)
Upload attachments
To send attachments first upload the attachments as base64 encoded strings and use the returned attachment IDs when sending.
send_options = mailslurp_client.SendEmailOptions(
to=[recipient.email_address],
subject="Hello",
body="Here is your email body",
attachments=attachment_ids,
)
sent = inbox_controller.send_email_and_confirm(
inbox_id=inbox.id, send_email_options=send_options
)
self.assertTrue(sent.sent_at is not None)
Receive emails and extract content
Use the wait for controller to wait for an expected email count to be satisfied and then return those emails.
email_controller = mailslurp_client.EmailControllerApi(api_client)
email = email_controller.get_email(email_id=email_id)
self.assertTrue("Hello" in email.subject)
Verify email address
You can verify email addresses with MailSlurp. This will perform SMTP queries for the email address on your behalf.
def test_validate_email(self):
with mailslurp_client.ApiClient(configuration) as api_client:
mailserver_controller = mailslurp_client.MailServerControllerApi(api_client)
verify_options = mailslurp_client.VerifyEmailAddressOptions(email_address="test@gmail.com")
result = mailserver_controller.verify_email_address(verify_options=verify_options)
assert result.error is None
assert result.is_valid is True