Skip to main content

Official MailSlurp Python SDK Email API

Project description

MailSlurp Python Client

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.

Quick links

Get started

This section describes how to get up and running with the Python client.

See the examples page for more examples and use with common frameworks such as Django, Flask and Pytest.

See the method documentation for a list of all functions

Create API Key

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.

Configure

Once installed you can import mailslurp_client and create a configuration with your API Key.

import mailslurp_client

configuration = mailslurp_client.Configuration()
configuration.api_key['x-api-key'] = "your-api-key-here"

Common usage

MailSlurp can be used to create email addresses than can send and receive real emails and attachments in Python.

Create an email address

Use with statements to create controllers for each endpoint of the MailSlurp API.

def create_inbox_example():
    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

Inbox types

Inboxes can be either SMTP or HTTP type. Set the inbox type using the inboxType property. SMTP inboxes are handled by a custom mailserver and support a wide range of clients while HTTP inboxes use Amazon SES and don't support some older clients like Outlook. SMTP inboxes are recommended for public facing email addresses while HTTP inboxes are best for application testing. Please see the guide on types of inboxes for more information.

List inboxes

def test_can_list_inboxes(self):
    # use the with keyword to create an api client
    with mailslurp_client.ApiClient(configuration) as api_client:
        # create an inbox using the inbox controller
        inbox_controller = mailslurp_client.InboxControllerApi(api_client)
        inboxes = inbox_controller.get_all_inboxes(page=0)

        # pagination properties
        assert inboxes.total_pages > 0
        assert inboxes.total_elements > 0

        # view contents
        assert len(inboxes.content[0].id) > 0

Send emails

def send_email_example():
    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 = "Your message"
        send_email_options.is_html = True
        api_instance.send_email(inbox.id, send_email_options=send_email_options)

Send email using SMTP

To use SMTP clients first create an SMTP type inbox and use the inbox controller get_imap_smtp_access method to obtain the username, password, port and host.

import os
import mailslurp_client
from smtplib import SMTP
from mailslurp_client import CreateInboxDto

api_key = os.environ.get('API_KEY')
assert api_key is not None

# create a mailslurp configuration
configuration = mailslurp_client.Configuration()
configuration.api_key['x-api-key'] = api_key


class Test_MailSlurp_SDK:
    # Can send email with SMTP
    def test_can_send_with_smtp(self):
        with mailslurp_client.ApiClient(configuration) as api_client:
            # create an SMTP inbox
            inbox_controller = mailslurp_client.InboxControllerApi(api_client)
            inbox1 = inbox_controller.create_inbox_with_options(CreateInboxDto(inbox_type="SMTP_INBOX"))
            inbox2 = inbox_controller.create_inbox()
            assert "@mailslurp.mx" in inbox1.email_address

            # get smtp imap access
            smtp_access = inbox_controller.get_imap_smtp_access(inbox_id=inbox1.id)
            msg = "Subject: Test subject

This is the body"

            # configure smtp client using access details
            with SMTP(host=smtp_access.smtp_server_host, port=smtp_access.smtp_server_port) as smtp:
                smtp.login(user=smtp_access.smtp_username, password=smtp_access.smtp_password)
                smtp.sendmail(from_addr=inbox1.email_address, to_addrs=[inbox2.email_address], msg=msg)
                smtp.quit()

            # test that email is sent
            wait_for_controller = mailslurp_client.WaitForControllerApi(api_client)
            email = wait_for_controller.wait_for_latest_email(inbox_id=inbox2.id)
            assert "Test subject" in email.subject

Use attachments

To send attachments first use the AttachmentControllerApi to upload a file or byte stream. Then use the attachment ID returned with subsequent send calls.

@staticmethod
def upload_attachment():
    with mailslurp_client.ApiClient(configuration) as api_client:
        import base64

        file_bytes = "Your file's bytes".encode("utf-8")
        encoded_contents = base64.b64encode(file_bytes)
        attachment_controller = mailslurp_client.AttachmentControllerApi(api_client)

        upload_options = mailslurp_client.UploadAttachmentOptions(
            content_type="text/plain",
            filename="test.txt",
            base64_contents=str(encoded_contents, 'utf-8')
        )
        print("upload_options = {}".format(upload_options))
        return attachment_controller.upload_attachment(upload_options)

Receive emails and extract content

def receive_email_and_extract_content_example():
    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"
        send_email_options.attachments = self.upload_attachment() # see previous section

        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
        import re
        pattern = re.compile('Your code is: ([0-9]{3})')
        matches = pattern.match(email.body)
        code = matches.group(1)

        assert code == "123"

Download attachments

def receive_email_and_extract_content_example():
    with mailslurp_client.ApiClient(configuration) as api_client:
        # wait for email to be received by inbox 2
        email = wait_controller.wait_for_latest_email(inbox_id=inbox_2.id, timeout=30000, unread_only=True)

        # assert that the message was received
        assert email.inbox_id == inbox_2.id
        assert email.subject == "Hello"

        # attachment ids pressent
        assert len(email.attachments) == 1

        # download attachment content
        email_controller = mailslurp_client.EmailControllerApi(api_client)
        downloaded_bytes = email_controller.download_attachment(email.attachments[0], email.id)
        assert len(downloaded_bytes) > 0

        # alternatively download as base64 string with more meta data
        email_controller = mailslurp_client.EmailControllerApi(api_client)
        downloaded_attachment = email_controller.download_attachment_base64(email.attachments[0], email.id)
        assert downloaded_attachment.content_type == "text/plain"
        base64_contents = downloaded_attachment.base64_file_contents
        import base64
        attachment_bytes = base64.b64decode(base64_contents)
        assert len(attachment_bytes) > 0

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

SDK Documentation

See the guides page or the examples or the Method Documentation for full usage.

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

mailslurp-client-15.15.2.tar.gz (247.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

mailslurp_client-15.15.2-py3-none-any.whl (544.1 kB view details)

Uploaded Python 3

File details

Details for the file mailslurp-client-15.15.2.tar.gz.

File metadata

  • Download URL: mailslurp-client-15.15.2.tar.gz
  • Upload date:
  • Size: 247.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.8.6

File hashes

Hashes for mailslurp-client-15.15.2.tar.gz
Algorithm Hash digest
SHA256 b8a783fe806299db0a1421abb1c37737cefb131f1ba10b1c3bd10ce8422e703b
MD5 81ded4cc75868fc968ce772bb122d911
BLAKE2b-256 43e91b04819a00fb06e09264f3fa8fb9f6c98f7dbda3a46021bef863891d29d5

See more details on using hashes here.

File details

Details for the file mailslurp_client-15.15.2-py3-none-any.whl.

File metadata

File hashes

Hashes for mailslurp_client-15.15.2-py3-none-any.whl
Algorithm Hash digest
SHA256 d259575645d6f608827b4c9a74c860af35e4c9d99a62086d4284d026fff6e1c6
MD5 9d0c1a35207d506accb4468dcb041866
BLAKE2b-256 2c76e40dde01fdb5334fe1352c74b06ec675eb7d7b107200c7e8d10380363853

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page