Getting started overview
Mailtrap offers two primary services: Email Testing (an SMTP sandbox) and Email Sending (an Email API/SMTP service). This guide focuses on the initial setup for both, enabling developers to quickly integrate Mailtrap into their workflows for development, testing, and production email delivery.
The process generally involves creating a Mailtrap account, obtaining API tokens or SMTP credentials, and then configuring your application or script to interact with Mailtrap's endpoints. Mailtrap provides client libraries (SDKs) for several programming languages to simplify integration.
To begin, you will need to decide whether you are setting up the Email Testing service to catch and inspect emails during development, or the Email Sending service for delivering emails to recipients in a production environment. Both services have distinct setup procedures and credentials.
Quick Reference Guide
| Step | What to Do | Where |
|---|---|---|
| 1. Account Creation | Sign up for a Mailtrap account. | Mailtrap Registration Page |
| 2. Service Selection | Choose between Email Testing (Sandbox) or Email Sending. | Mailtrap Dashboard |
| 3. Credential Retrieval | Get API token (for API) or SMTP credentials (for SMTP). | Mailtrap Dashboard > Inboxes (for Testing) or Sending Domains (for Sending) |
| 4. Integration | Configure your application using SDK or direct SMTP. | Your application's codebase |
| 5. First Request | Send a test email. | Your application's codebase; verify in Mailtrap Inbox |
Create an account and get keys
Accessing Mailtrap's services requires an account. You can register for a free tier to explore the features before committing to a paid plan. The free tier offers 100 emails per day and one inbox for Email Testing, and 1,000 emails per month for Email Sending.
Account Creation
- Navigate to the Mailtrap registration page.
- Provide your email address and create a password, or sign up using an existing Google or GitHub account.
- Confirm your email address if prompted.
Obtaining Credentials for Email Testing (Sandbox)
For Email Testing, Mailtrap provides virtual inboxes that capture emails sent via SMTP. You will need the SMTP credentials for your specific inbox.
- After logging in, go to the Email Testing section on your dashboard.
- Select an existing inbox or create a new one.
- Inside the inbox, locate the SMTP Settings tab. Here you will find the
Host,Port,Username, andPassword. These are the credentials your application will use to send emails to the Mailtrap sandbox.
Obtaining Credentials for Email Sending (API/SMTP Service)
For sending production emails, Mailtrap offers an Email API and an SMTP service. You will need an API token for API usage or specific SMTP credentials for the SMTP service.
- From your dashboard, navigate to the Email Sending section.
- You must first add and verify a sending domain. Follow the instructions to add your domain and complete the DNS verification process (e.g., adding MX, SPF, DKIM records). This step is crucial for email deliverability and authentication, as detailed in Cloudflare's DNS record management guide.
- Once your domain is verified, you can generate an API token or retrieve SMTP credentials:
- For API: Go to API Tokens under your sending domain settings. Generate a new token. This token will be used in the
Authorizationheader for API requests. - For SMTP: Access the SMTP Settings for your verified domain. You will find the
Host,Port,Username, andPasswordunique to your sending domain.
- For API: Go to API Tokens under your sending domain settings. Generate a new token. This token will be used in the
Your first request
This section demonstrates how to send a basic email using both the Email Testing sandbox and the Email Sending API. We will use Python for the examples, but Mailtrap provides SDKs for other languages including Ruby, PHP, Node.js, Go, Java, and C#.
Email Testing (Sandbox) Example (Python via SMTP)
This example sends an email to your Mailtrap sandbox using Python's smtplib. Replace placeholder values with your actual Mailtrap SMTP credentials.
import smtplib
from email.mime.text import MIMEText
# Mailtrap SMTP credentials for your inbox
MAILTRAP_USERNAME = "YOUR_MAILTRAP_USERNAME" # From your inbox SMTP settings
MAILTRAP_PASSWORD = "YOUR_MAILTRAP_PASSWORD" # From your inbox SMTP settings
MAILTRAP_HOST = "sandbox.smtp.mailtrap.io"
MAILTRAP_PORT = 2525 # Or 465 for SSL, 587 for TLS
# Email details
SENDER_EMAIL = "[email protected]"
RECIPIENT_EMAIL = "[email protected]" # Any email will be caught by Mailtrap sandbox
SUBJECT = "Test Email from Mailtrap Sandbox"
BODY = "This is a test email sent to the Mailtrap sandbox."
msg = MIMEText(BODY)
msg["Subject"] = SUBJECT
msg["From"] = SENDER_EMAIL
msg["To"] = RECIPIENT_EMAIL
try:
with smtplib.SMTP(MAILTRAP_HOST, MAILTRAP_PORT) as server:
server.starttls() # Use starttls for port 587 or 2525; for 465 use SMTP_SSL
server.login(MAILTRAP_USERNAME, MAILTRAP_PASSWORD)
server.send_message(msg)
print("Email sent successfully to Mailtrap sandbox!")
except Exception as e:
print(f"Failed to send email: {e}")
After running this script, log into your Mailtrap dashboard and check the selected inbox within the Email Testing section. You should see the sent email captured there.
Email Sending (API) Example (Python via Requests)
This example demonstrates sending a transactional email using Mailtrap's Email Sending API with a Python requests library. Replace YOUR_API_TOKEN and other placeholders with your actual values from the Email Sending section of your Mailtrap account.
import requests
import json
# Mailtrap Email Sending API details
API_ENDPOINT = "https://send.api.mailtrap.io/api/send"
API_TOKEN = "YOUR_API_TOKEN" # From Email Sending API Tokens
# Email details
SENDER_NAME = "Mailtrap Test"
SENDER_EMAIL = "[email protected]" # Must be a verified sending domain
RECIPIENT_NAME = "Recipient Name"
RECIPIENT_EMAIL = "[email protected]"
SUBJECT = "Production Test Email via Mailtrap API"
BODY_HTML = "<p>This is a test email sent via Mailtrap <strong>Email Sending API</strong>.</p>"
BODY_TEXT = "This is a test email sent via Mailtrap Email Sending API."
headers = {
"Authorization": f"Bearer {API_TOKEN}",
"Content-Type": "application/json"
}
payload = {
"from": {
"email": SENDER_EMAIL,
"name": SENDER_NAME
},
"to": [
{
"email": RECIPIENT_EMAIL,
"name": RECIPIENT_NAME
}
],
"subject": SUBJECT,
"html": BODY_HTML,
"text": BODY_TEXT
}
try:
response = requests.post(API_ENDPOINT, headers=headers, data=json.dumps(payload))
response.raise_for_status() # Raise an exception for HTTP errors
print("Email sent successfully via Mailtrap API!")
print(f"Response: {response.json()}")
except requests.exceptions.HTTPError as http_err:
print(f"HTTP error occurred: {http_err} - {response.text}")
except Exception as err:
print(f"An error occurred: {err}")
Upon successful execution, the email will be sent to [email protected]. You can verify the delivery status and analytics in the Mailtrap Email Sending dashboard.
Common next steps
Once you have successfully sent your first email, you can explore more advanced features and integrations:
- Integrate with CI/CD: Automate email testing within your continuous integration/continuous deployment pipelines. Mailtrap's sandbox can be used for automated checks of email content.
- Webhooks: Set up webhooks to receive notifications about email events, such as delivery, opens, and clicks for Email Sending, or new email arrivals for Email Testing. Consult the Mailtrap webhooks documentation for configuration details.
- Email Templates: Utilize Mailtrap's template management features for Email Sending to create and manage reusable email layouts, which can be populated with dynamic data via the API.
- Spam Analysis and HTML Check: For Email Testing, leverage the built-in spam score checker and HTML/CSS validation tools to ensure your emails render correctly and avoid spam filters.
- Advanced Analytics: Monitor email performance metrics like open rates, click rates, and bounce rates through the Mailtrap Email Sending dashboard.
- API Reference Exploration: Review the comprehensive Mailtrap API reference for all available endpoints and parameters for both testing and sending services.
- SDK Exploration: If you used direct SMTP or HTTP requests, consider using one of Mailtrap's official SDKs for your preferred language, which can streamline integration and error handling.
Troubleshooting the first call
Encountering issues during the initial setup is common. Here are some troubleshooting tips for Mailtrap:
- Incorrect Credentials: Double-check that the SMTP username, password, host, and port, or the API token, are copied precisely from your Mailtrap dashboard. Ensure you are using the correct credentials for the specific service (Testing vs. Sending).
- Firewall or Network Restrictions: Your local network or server firewall might be blocking outbound connections on the SMTP ports (e.g., 25, 465, 587, 2525). Verify that these ports are open.
- SSL/TLS Configuration: Ensure you are using the correct encryption method (
STARTTLSfor ports 587/2525 orSSLfor port 465) and that your client library is configured to use it. Mismatched encryption can lead to connection failures. - Verified Sending Domain (Email Sending): For the Email Sending API or SMTP service, your 'From' email address must belong to a domain that you have verified within Mailtrap. Unverified domains will result in sending failures. Check your DNS records (MX, SPF, DKIM) for correct configuration.
- API Token Permissions: If using the API, ensure your API token has the necessary permissions for sending emails. Mailtrap allows granular control over token permissions.
- Syntax Errors in Code: Review your code for any typos or incorrect syntax, especially in API request bodies or SMTP client configurations.
- Check Mailtrap Logs: For Email Sending, the Mailtrap dashboard provides logs and delivery statuses that can offer insights into why an email failed to send. For Email Testing, if an email doesn't appear, ensure your application is configured to send to the Mailtrap sandbox SMTP server.
- Consult Documentation: Refer to the official Mailtrap documentation for specific error codes and detailed troubleshooting guides.