Skip to main content

test PyPI downloads

Official Mailtrap Python client

This Python package offers integration with the official API for Mailtrap.

Add email sending functionality to your Python application quickly with Mailtrap.

Compatibility with previous releases

Versions of this package up to 1.0.1 were different, unrelated project, that is now maintained as Sendria. To continue using it, see instructions.

Installation

Prerequisites

  • Python version 3.10+

Install package

pip install mailtrap

Usage

Minimal usage (Transactional sending)

import mailtrap as mt

API_TOKEN = "<YOUR_API_TOKEN>"  # your API key here https://mailtrap.io/api-tokens

client = mt.MailtrapClient(token=API_TOKEN)

# Create mail object
mail = mt.Mail(
    sender=mt.Address(email="sender@example.com", name="John Smith"),
    to=[mt.Address(email="recipient@example.com")],
    subject="You are awesome!",
    text="Congrats for sending test email with Mailtrap!",
)

client.send(mail)

Sandbox vs Production (easy switching)

Mailtrap lets you test safely in the Email Sandbox and then switch to Production (Sending). Remove the inbox_id field or set it to None. Then, remove the sandbox field or set it to False. You can change the arguments in the code or via another way. Here is an example using environment variables.

Set next environment variables:

MAILTRAP_API_KEY=your_api_token # https://mailtrap.io/api-tokens
MAILTRAP_USE_SANDBOX=true       # true/false toggle
MAILTRAP_INBOX_ID=123456        # Only needed for sandbox

Bootstrap logic:

import os
import mailtrap as mt

API_KEY = os.environ["MAILTRAP_API_KEY"]
IS_SANDBOX = os.environ.get("MAILTRAP_USE_SANDBOX", "true").lower() == "true"
INBOX_ID = os.environ.get("MAILTRAP_INBOX_ID")

client = mt.MailtrapClient(
  token=API_KEY,
  sandbox=IS_SANDBOX,
  inbox_id=INBOX_ID,  # None is ignored for production
)

# Create mail object
mail = mt.Mail(
    sender=mt.Address(email="sender@example.com", name="John Smith"),
    to=[mt.Address(email="recipient@example.com")],
    subject="You are awesome!",
    text="Congrats for sending test email with Mailtrap!",
)

client.send(mail)

Bulk stream example (optional) differs only by setting bulk=True: bulk_client = mt.MailtrapClient(token=API_KEY, bulk=True)

Recommendations:

  • Use separate API tokens for Production and Sandbox.
  • Keep initialisation in a single factory object/service so that switching is centralised.
import base64
import os
from pathlib import Path

import mailtrap as mt

client = mt.MailtrapClient(token=os.environ["MAILTRAP_API_KEY"])

welcome_image = Path(__file__).parent.joinpath("welcome.png").read_bytes()


mail = mt.Mail(
    sender=mt.Address(email="mailtrap@example.com", name="Mailtrap Test"),
    to=[mt.Address(email="your@email.com", name="Your name")],
    cc=[mt.Address(email="cc@email.com", name="Copy to")],
    bcc=[mt.Address(email="bcc@email.com", name="Hidden Recipient")],
    subject="You are awesome!",
    text="Congrats for sending test email with Mailtrap!",
    html="""
    <!doctype html>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      </head>
      <body style="font-family: sans-serif;">
        <div style="display: block; margin: auto; max-width: 600px;" class="main">
          <h1 style="font-size: 18px; font-weight: bold; margin-top: 20px">
            Congrats for sending test email with Mailtrap!
          </h1>
          <p>Inspect it using the tabs you see above and learn how this email can be improved.</p>
          <img alt="Inspect with Tabs" src="cid:welcome.png" style="width: 100%;">
          <p>Now send your email using our fake SMTP server and integration of your choice!</p>
          <p>Good luck! Hope it works.</p>
        </div>
        <!-- Example of invalid for email html/css, will be detected by Mailtrap: -->
        <style>
          .main { background-color: white; }
          a:hover { border-left-width: 1em; min-height: 2em; }
        </style>
      </body>
    </html>
    """,
    category="Test",
    attachments=[
        mt.Attachment(
            content=base64.b64encode(welcome_image),
            filename="welcome.png",
            disposition=mt.Disposition.INLINE,
            mimetype="image/png",
            content_id="welcome.png",
        )
    ],
    headers={"X-MT-Header": "Custom header"},
    custom_variables={"year": 2023},
)

client.send(mail)

Minimal usage of email template

import os
import mailtrap as mt

client = mt.MailtrapClient(token=os.environ["MAILTRAP_API_KEY"])

# create mail object
mail = mt.MailFromTemplate(
    sender=mt.Address(email="mailtrap@example.com", name="Mailtrap Test"),
    to=[mt.Address(email="your@email.com")],
    template_uuid="2f45b0aa-bbed-432f-95e4-e145e1965ba2",
    template_variables={"user_name": "John Doe"},
)

client.send(mail)

Sending email directly via SendingApi

This approach is newer. It can be useful when you expect the response to be model-based rather than dictionary-based, as in MailtrapClient.send().

import os
import mailtrap as mt

client = mt.MailtrapClient(token=os.environ["MAILTRAP_API_KEY"])
sending_api = client.sending_api

# create mail object
mail = mt.Mail(
    sender=mt.Address(email="sender@example.com", name="John Smith"),
    to=[mt.Address(email="recipient@example.com")],
    subject="You are awesome!",
    text="Congrats for sending test email with Mailtrap!",
)

sending_api.send(mail)

Mailtrap sending responses difference

1. client.send()

Response:

{
  "success": True,
  "message_ids": ["5162954175"]
}

2. client.sending_api.send()

Response:

SendingMailResponse(success=True, message_ids=["5162955057"])

The same situation applies to both client.batch_send() and client.sending_api.batch_send().

Supported functionality & Examples

Email API:

Email Sandbox (Testing) API:

Contacts API:

Email Templates API:

Sending Domains API:

Inbound Email API:

Email Campaigns API:

Webhooks API:

Suppressions API:

Stats API:

Email Logs API:

General API:

Organizations API:

Contributing

Bug reports and pull requests are welcome on GitHub. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the code of conduct.

Development Environment

Clone the repo

git clone https://github.com/mailtrap/mailtrap-python.git
cd mailtrap-python

Install tox

tox is an environment orchestrator. We use it to setup local environments, run tests and execute linters.

python -m pip install --user tox
python -m tox --help

To setup virtual environments, run tests and linters use:

tox

It will create virtual environments with all installed dependencies for each available python interpreter (starting from python3.10) on your machine. By default, they will be available in {project}/.tox/ directory. So, for instance, to activate python3.11 environment, run the following:

source .tox/py311/bin/activate

Information for version 1 users

If you are a version 1 user, it is advised that you upgrade to Sendria, which is the same package, but under a new name, and with new features. However, you can also continue using the last v1 release by locking the version in pip:

# To use the FORMER version of the mailtrap package, now known as Sendria:
pip install --force-reinstall -v "mailtrap==1.0.1"

License

The project is available as open source under the terms of the MIT License.

Code of Conduct

Everyone interacting in the Mailtrap project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct

Metadata

Release files for mailtrap 3.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for mailtrap 3.0.0
File Size Uploaded Provenance Actions
mailtrap-3.0.0.tar.gz 42.2 kB Without provenance Details for mailtrap-3.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for mailtrap 3.0.0
File Interpreter ABI Platform Actions
mailtrap-3.0.0-py3-none-any.whl Python 3 none any Details for mailtrap-3.0.0-py3-none-any.whl

Total release size: 109.7 kB

Release files / mailtrap-3.0.0.tar.gz

Download URL mailtrap-3.0.0.tar.gz
Size 42.2 kB
Tags Source
SHA-256 checksum
How to use checksums
8e4bfa9a8dd40b48b7284c3399324a49c35523508199857bfcaa1b81b6704cb8
BLAKE2b-256 checksum
How to use checksums
f975028900169843450c1d7820848a3d81b851db8d7e514d80dae6a811ae1770
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.6 {"installer":{"name":"uv","version":"0.13.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / mailtrap-3.0.0-py3-none-any.whl

Download URL mailtrap-3.0.0-py3-none-any.whl
Size 67.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
fc598167cae2a5c3084acdd21c8d71e0c8f35f4a559bf43d1b4f492adc654b19
BLAKE2b-256 checksum
How to use checksums
db43d340875245711671ac5ce7fac3c34fe45c7abf35a85cc4bf05e4c11d228a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.6 {"installer":{"name":"uv","version":"0.13.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for mailtrap 3.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

3.0.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page