How to Send Emails with Email API: Practical Examples in Popular Languages and Frameworks
In this article, I’ll show you how to send emails using an email API in various programming languages and frameworks.
I’ll also break down the differences between SMTP and email APIs, but if you’re already aware of them and your needs, feel free to skip ahead by clicking on some of the following links:
Note that as my API of choice, I’ll be using Email API, a part of the Mailtrap Email Delivery Platform. However, the core principles in this article can be applied to any email API provider.
Setting up Mailtrap Email API
Mailtrap Email API is based on the REST principles, which classifies it as REST, or RESTful API. These types of APIs offer greater flexibility and, as you’ll notice, are super easy to work with as they use standard HTTP methods (e.g., GET, POST, PUT, DELETE), which most developers are familiar with.
Here’s what you need to do to get started with Mailtrap API and integrate it into your project:
Sign up for a free Mailtrap account: You can sign up using your Google, GitHub, or Office 365 accounts, or, if you prefer, simply use your email address.
Verify your domain: Navigate to the “Sending Domains” tab and click “Add Domain.” Enter your domain name and confirm by clicking the “Add” button.
Update DNS records: Mailtrap will provide and automatically authenticate specific DNS records (SPF, DKIM, DMARC) that should be added to your domain provider’s DNS settings.
Tip: here’s a detailed Getting Started Guide to help you out. 👀
Once your domain is verified, you can integrate your application with Mailtrap’s Email API.
Access API credentials: Go to the Sending Domains tab, select your verified domain, and open the “Integration” tab. Here, you’ll find credentials for both Transactional and Bulk streams.
Build your HTTP request: Use the provided API credentials to configure an authenticated HTTP request in your preferred programming language or framework.
Run your script: Execute your email sending script. If everything is set up correctly, your email will land in the recipient’s inbox, and you will see it in the “Email Logs” section.
Note: Each domain has unique API tokens. To manage these, go to Settings → API Tokens and click “Add Token” if you need additional tokens. Additionally, Mailtrap’s API supports email templates, attachments, custom variables, and email categories. For detailed information, check the API documentation.
Send emails in PHP
For a comprehensive guide on sending emails in PHP, read the full article here
Since we already covered the Mailtrap installation process, let’s start by integrating the Mailtrap PHP SDK.
First, install Mailtrap PHP SDK using one of the following Composer commands:
With Symfony HTTP client:
composer require railsware/mailtrap-php symfony/http-client nyholm/psr7
With Guzzle HTTP client:
composer require railsware/mailtrap-php guzzlehttp/guzzle php-http/guzzle7-adapter
Note: Mailtrap API Client uses PSR-18 client abstraction and is thus not hard-coupled to any library that sends HTTP messages. It gives you the flexibility to choose which HTTP client you want to use.
However, it’s recommended to use Symfony for its fast performance, ease of use, flexibility, and strong community support.
Next, using the below code, you can send a plain text email using the Mailtrap PHP SDK:
<?php
use Mailtrap\Config;
use Mailtrap\EmailHeader\CategoryHeader;
use Mailtrap\EmailHeader\CustomVariableHeader;
use Mailtrap\Helper\ResponseHelper;
use Mailtrap\MailtrapClient;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;
use Symfony\Component\Mime\Header\UnstructuredHeader;
require __DIR__ . '/vendor/autoload.php';
// Your API token from here https://mailtrap.io/api-tokens
$apiKey = getenv('MAILTRAP_API_KEY');
$mailtrap = new MailtrapClient(new Config($apiKey));
$email = (new Email())
->from(new Address('example@your-domain-here.com', 'Mailtrap Test'))
->replyTo(new Address('reply@your-domain-here.com'))
->to(new Address('email@example.com', 'Jon')) // Single recipient
->priority(Email::PRIORITY_HIGH)
->subject('Best practices of building HTML emails')
->text('Hey! Learn the best practices of building HTML emails and play with ready-to-go templates. Mailtrap's Guide on How to Build HTML Email is live on our blog');
// Headers
$email->getHeaders()
->addTextHeader('X-Message-Source', 'domain.com')
->add(new UnstructuredHeader('X-Mailer', 'Mailtrap PHP Client')); // the same as addTextHeader
// Custom Variables
$email->getHeaders()
->add(new CustomVariableHeader('user_id', '45982'))
->add(new CustomVariableHeader('batch_id', 'PSJ-12'));
// Category (should be only one)
$email->getHeaders()
->add(new CategoryHeader('Integration Test'));
try {
$response = $mailtrap->sending()->emails()->send($email); // Email sending API (real)
var_dump(ResponseHelper::toArray($response)); // body (array)
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
This script initializes the Mailtrap client with your API key, which can be found in the Integration tab under the Sending Domains section.
It then creates a new email message and sets various properties, such as the sender
, recipient
, subject
, and content
. Additionally, it adds custom headers and variables.
Finally, the script sends the email using the send() function
and outputs the response or an error message if the email fails to send.
…
Test emails and email sending on staging
This article has ~4,000 words and about 50% of that is code only. Considering this, you can easily imagine the not-so-small potential for errors while implementing the code into your app.
Hence, it’s of utmost importance to test your email-sending functionality. This is an industry-standard practice that ensures your code works properly, your emails are going where they’re supposed to while avoiding spam filters, and much more.
Consider it as tasting a dish you’ve just prepared. After putting in all the effort to make it, you wouldn’t want to serve an omelette that’s not salty at all, would you? 🧂
For this purpose, especially if you’ve used our email API for sending, I recommend using Mailtrap Testing API.
Via Mailtrap Testing API, you can run the following commands:
Inbox – Create new inboxes, reset credentials, receive messages, clean one or all messages in the inbox, mark messages as read, and manage users.
Project – Create new projects, update/delete them, and manage their users.
Email content – Inspect the raw HTML (you can also download it), text, and get detailed info about the HTML part, including a list of possible errors, along with message attachments.
Bcc and message headers – Receive and test message headers.
Deliverability – You get a SPAM report, domain blacklisting details, and a spam score, which if you keep under 5, can proactively solve potential problems such as hitting the spam filters and ending up in the junk folder.
With the Email Testing API, you can also test your templates. Simply enable sandbox, specify the inbox ID, receive template test, and then send it through the API in the production environment.
Lastly, Mailtrap Email Testing API is quite easy to integrate for testing, automation, and testing automated sequences.
For example, here’s how you would test emails using Python and Mailtrap Email Testing API:
Establish a connection to the API endpoint using
http.client.HTTPSConnection
.Define your email content (e.g., recipients, sender, subject, text content, attachments, etc.)
Make a POST request to the API with your payload and necessary headers, including your API token for authorization. Here’s how it looks in practice:
import http.client
import json
def test_send_email():
conn = http.client.HTTPSConnection("sandbox.api.mailtrap.io")
payload = {
"to": [{"email": "john_doe@example.com", "name": "John Doe"}],
"cc": [{"email": "jane_doe@example.com", "name": "Jane Doe"}],
"bcc": [{"email": "james_doe@example.com", "name": "Jim Doe"}],
"from": {"email": "sales@example.com", "name": "Example Sales Team"},
"attachments": [
{
"content": "base64_encoded_content_here",
"filename": "index.html",
"type": "text/html",
"disposition": "attachment"
}
],
"custom_variables": {"user_id": "45982", "batch_id": "PSJ-12"},
"headers": {"X-Message-Source": "dev.mydomain.com"},
"subject": "Your Example Order Confirmation",
"text": "Congratulations on your order no. 1234",
"category": "API Test"
}
headers = {
'Content-Type': "application/json",
'Accept': "application/json",
'Api-Token': "your_api_token_here" # Replace with your real API token
}
# Convert the payload to a JSON string
json_payload = json.dumps(payload)
# Make the POST request
conn.request("POST", "/api/send/inbox_id", json_payload, headers) # Replace 'inbox_id' with your real inbox ID
# Get the response
response = conn.getresponse()
data = response.read()
print(data.decode("utf-8"))
if __name__ == "__main__":
test_send_email()
Of course, if you’re interested in more information, be sure to check the API docs for details on API testing.
Test Emails with Mailtrap for Free
Wrapping up
Whether you’ve opted for sending emails with API or, perhaps, with SMTP, I hope you now have a better understanding of the intricacies involved in the email backend.
And one more thing: I heartily invite you to further explore our blog, where you can learn how to send emails in various languages and frameworks and read articles such as:
We appreciate you chose this part of the article to find out how to send emails in PHP with API. To find out how to do it in other languages, read the full version of the article on Mailtrap blog!