Authentication overview

Mailtrap provides distinct authentication mechanisms tailored for its two primary services: Email Testing (SMTP Sandbox) and Email Sending (Email API/SMTP Service). These methods ensure secure access to user-specific inboxes, testing environments, and transactional email sending infrastructure. The choice of authentication method depends on the specific Mailtrap service being used and the integration approach, whether through direct API calls or SMTP client configurations.

For programmatic access to Mailtrap's features, such as managing inboxes or sending emails via its API, users typically employ API tokens. These tokens act as unique identifiers and secret keys, granting permissions to specific resources within a user's Mailtrap account. When establishing direct connections from an email client or application to Mailtrap's SMTP servers, standard username and password credentials are used, often in conjunction with TLS encryption to secure the communication channel. Both approaches are designed to integrate seamlessly into various development and production environments, supporting a range of SDKs across multiple programming languages including Ruby SDK examples and Python API integration guides.

Supported authentication methods

Mailtrap supports the following authentication methods to secure access to its Email Testing and Email Sending services:

Method When to Use Security Level
API Token For Mailtrap Email Sending API and Email Testing API (HTTP requests). Ideal for server-to-server communication, custom integrations, and programmatic access to Mailtrap features. High. Requires secure handling of tokens, typically passed in HTTP headers. Supports token rotation and granular permissions (for some token types).
SMTP Username/Password For connecting to Mailtrap's SMTP servers for both Email Testing (Sandbox) and Email Sending. Used by email clients, applications, and frameworks configured to send email via SMTP. Moderate to High. Security is enhanced significantly when combined with Transport Layer Security (TLS) encryption, which is standard practice for modern SMTP configurations.

For API interactions, Mailtrap's API tokens are typically supplied in the Authorization header using the Bearer scheme. This is a common practice for RESTful APIs, as detailed in the OAuth 2.0 Bearer Token Usage specification. For SMTP, traditional username and password authentication over a TLS-encrypted connection is the standard approach, offering protection against eavesdropping and tampering during transit.

Getting your credentials

Accessing your authentication credentials for Mailtrap involves navigating the user interface within your Mailtrap account. The process is straightforward for both API tokens and SMTP credentials, but they are located in different sections corresponding to their respective services.

For API Tokens (Email Sending API & Email Testing API)

  1. Log In: Sign into your Mailtrap account on the Mailtrap website.
  2. Navigate to API Tokens: For the Email Sending API, go to the 'Sending Domains' section, select a domain, and find the API tokens associated with it. For the Email Testing API, tokens are generally available under the 'API' section within the sandbox project settings.
  3. Generate/Retrieve Token: If you don't have an existing token, you can generate a new one. Mailtrap often allows you to create multiple tokens and assign specific permissions or associate them with different projects or domains, enhancing security and organization.
  4. Copy Token: Once generated, copy the API token. It's crucial to store this token securely, as it grants access to your Mailtrap account's capabilities.

For SMTP Username/Password (Email Testing Sandbox & Email Sending SMTP)

  1. Log In: Access your Mailtrap account.
  2. Select Service:
    • For Email Testing (Sandbox): Navigate to a specific inbox within your 'Email Testing' project. The SMTP credentials (host, port, username, password) are usually displayed prominently on the 'SMTP Settings' tab for that inbox. Each sandbox inbox has its own unique set of credentials.
    • For Email Sending (SMTP Service): Go to the 'Sending Domains' section. After selecting a verified sending domain, you will find the SMTP credentials (host, port, username, password) for that domain. These credentials are used for sending production emails.
  3. Copy Credentials: Copy the username and password provided. Note that the password might be hidden and require an explicit click to reveal.

Mailtrap's documentation provides specific, up-to-date instructions on setting up SMTP for email sending and configuring the email testing sandbox, which include details on where to find these credentials.

Authenticated request example

This example demonstrates how to send an email using the Mailtrap Email Sending API with an API token, using Python and the popular requests library. This method is suitable for server-side applications that integrate directly with the Mailtrap API.


import requests

MAILTRAP_API_TOKEN = "YOUR_MAILTRAP_API_TOKEN"
SENDER_EMAIL = "[email protected]"
RECIPIENT_EMAIL = "[email protected]"

def send_email_with_mailtrap_api(api_token, sender, recipient, subject, body):
    url = "https://send.api.mailtrap.io/api/send"
    headers = {
        "Authorization": f"Bearer {api_token}",
        "Content-Type": "application/json"
    }
    payload = {
        "from": {
            "email": sender,
            "name": "Mailtrap Test"
        },
        "to": [
            {
                "email": recipient
            }
        ],
        "subject": subject,
        "text": body,
        "category": "API_Test"
    }

    try:
        response = requests.post(url, headers=headers, json=payload)
        response.raise_for_status()  # Raise an exception for HTTP errors
        print(f"Email sent successfully! Response: {response.json()}")
    except requests.exceptions.HTTPError as e:
        print(f"HTTP error occurred: {e}")
        print(f"Response content: {response.text}")
    except requests.exceptions.ConnectionError as e:
        print(f"Connection error occurred: {e}")
    except requests.exceptions.Timeout as e:
        print(f"Timeout error occurred: {e}")
    except requests.exceptions.RequestException as e:
        print(f"An unexpected error occurred: {e}")

# Example usage:
send_email_with_mailtrap_api(
    MAILTRAP_API_TOKEN,
    SENDER_EMAIL,
    RECIPIENT_EMAIL,
    "Hello from Mailtrap API!",
    "This is a test email sent using the Mailtrap Email Sending API with an API token."
)

This Python snippet demonstrates how an API token is included in the Authorization header as a Bearer token. This is the standard practice for authenticating requests to the Mailtrap Email Sending API. For a comprehensive list of API endpoints and request parameters, refer to the Mailtrap API reference documentation.

Security best practices

Implementing robust security practices when handling Mailtrap authentication credentials is crucial to protect your email infrastructure from unauthorized access and potential abuse.

  • API Token Management:
    • Environment Variables: Store API tokens in environment variables rather than hardcoding them directly into your application's source code. This prevents tokens from being exposed in version control systems or publicly accessible repositories.
    • Restricted Permissions: If Mailtrap supports it (which it does for some token types), generate API tokens with the minimum necessary permissions required for the task. For example, a token used only for sending emails should not have permissions to manage users or billing.
    • Regular Rotation: Periodically rotate your API tokens. This limits the window of opportunity for an attacker if a token is compromised.
    • Secure Transmission: Always ensure API requests are made over HTTPS to encrypt the token during transit, protecting it from interception. The Mailtrap API always uses HTTPS.
  • SMTP Credential Management:
    • Dedicated Credentials: For different applications or environments (development, staging, production), use distinct SMTP usernames and passwords where possible. This isolates potential compromises.
    • TLS Encryption: Always connect to Mailtrap's SMTP servers using Transport Layer Security (TLS) or its predecessor SSL. This encrypts the entire communication, including the username and password during authentication and the email content itself. Most modern email clients and libraries default to TLS for port 587 (submission) or 465 (SMTPS), but it's vital to confirm this in your configuration, as highlighted in Mozilla's TLS security explanation.
    • Avoid Public Exposure: Never expose your SMTP credentials in client-side code, public repositories, or unsecured configuration files.
  • Access Control and Monitoring:
    • Least Privilege: Ensure that only authorized personnel and systems have access to Mailtrap account credentials.
    • Audit Logs: Regularly review Mailtrap's activity logs (if available) to detect any unusual or unauthorized access patterns.
    • Strong Passwords: For your Mailtrap account login, use strong, unique passwords and enable multi-factor authentication (MFA) if offered, to add an extra layer of security beyond just static credentials.
  • SDK and Library Best Practices:
    • Official SDKs: Utilize Mailtrap's official SDKs (e.g., Ruby SDK, PHP SDK) when possible, as they are designed to handle authentication and communication securely.
    • Up-to-Date Libraries: Keep all related libraries and dependencies (e.g., HTTP client libraries, email sending libraries) updated to their latest versions to benefit from security patches and improvements.