Email Sending – Mailtrap https://mailtrap.io Modern email delivery for developers and product teams Tue, 28 Oct 2025 11:19:00 +0000 en-US hourly 1 https://mailtrap.io/wp-content/uploads/2023/01/cropped-favicon-1-32x32.png Email Sending – Mailtrap https://mailtrap.io 32 32 How to Send Emails in Bun.js: SMTP & Email API Methods Explained https://mailtrap.io/blog/bunjs-send-email/ Mon, 25 Aug 2025 08:50:29 +0000 https://mailtrap.io/?p=47075 In this tutorial, I’ll show you how to add email-sending functionality in Bun.js, a modern JavaScript runtime known for its speed and Node.js compatibility. 

More precisely, I’ll break down two primary ways to send emails in Bun.js:

Before diving in, ensure you have the following prerequisites:

Disclaimer: Every bit of code in this article has been prepared and tested by a developer before publication.

Ready to deliver your emails?
Try Mailtrap for Free

Send Email in Bun.js using Nodemailer

Using Nodemailer (a zero-dependency Node.js module for emails) with Bun lets you send emails via an SMTP server of your choice. This is useful if you want to use a solution like Mailtrap SMTP for developer and product teams. Focused on fast delivery and high inboxing rates for transactional and promo emails.

Let’s start with a simple use case: sending a plain-text email.

  • Install and import Nodemailer

Make sure Nodemailer is installed in your project. Then import it in your Bun script or application. For example, in an ES module context: import nodemailer from 'nodemailer';

  • Configure the SMTP transporter

Create a transporter object with your SMTP server details. This includes the host, port, and authentication credentials. You can find these credentials on your Mailtrap inbox’s SMTP settings page. 

Here’s how you might configure the transporter for Mailtrap’s sandbox SMTP:

import nodemailer from "nodemailer";

const transporter = nodemailer.createTransport({
  host: "live.smtp.mailtrap.io",
  port: 587,
  auth: {
    user: "1a2b3c4d5e6f7g",  // Mailtrap SMTP username (example)
    pass: "1a2b3c4d5e6f7g"   // Mailtrap SMTP password (example)
  }
});

Important: In the snippet above, make sure to replace the user and pass with your Mailtrap SMTP credentials. 

  • Configure the mailOptions

Define the email content and recipients in a mailOptions object. At minimum, specify the sender from, recipient(s) to, subject, and the body of the email. For a plain-text email, use the text field for the message. For example:

const mailOptions = {
  from: 'you@your-mailtrap-domain.com',               // sender address
  to: 'friend@example.com',              // list of receivers (comma-separated or array)
  subject: 'Hello from Bun.js!',         // Subject line
  text: 'This is a test email sent from a Bun.js app using Nodemailer.'  // plain text body
};
  • Send the email

Use the transporter’s sendMail() method to send the message. This method takes the mail options and a callback or returns a Promise. Here’s an example using a callback to log the result:

transporter.sendMail(mailOptions, (error, info) => {
  if (error) {
    console.error('Error:', error);
  } else {
    console.log('Email sent:', info.response);
  }
});

After updating index.ts file generated from project initialization, the final code would look like this:

import nodemailer from "nodemailer";

const transporter = nodemailer.createTransport({
  host: "live.smtp.mailtrap.io",
  port: 587,
  auth: {
    user: "api",
    pass: "1a2b3c4d5e6f7g",
  },
});

const mailOptions = {
  from: "you@example.com",
  to: "friend@example.com",
  subject: "Hello from Bun.js!",
  text: "This is a test email sent from a Bun.js app using Nodemailer.",
};

transporter.sendMail(mailOptions, (error, info) => {
  if (error) {
    console.error("Error:", error);
  } else {
    console.log("Email sent:", info.response);
  }
});

When you run your Bun script (e.g., bun run index.ts), this will attempt to send the email via the configured SMTP server. 

If successful, you should see a confirmation message with the SMTP server’s response. On error, it will log the error. Nodemailer takes care of the low-level SMTP commands for you, so sending an email is as easy as the above few steps.

(base) user@device bun % bun run index.ts
Email sent: 250 2.0.0 Ok: queued

Additionally, you can check the Mailtrap Email Logs to verify that the email has been sent properly.

With the basics covered for plain text, let’s see how to extend this to HTML emails, attachments, and multiple recipients.

Send HTML email

Nodemailer supports sending HTML emails by simply adding an html field to the mailOptions. The html field can contain your HTML string. It’s good practice to still include a plain-text version for email clients that prefer plain text.

For example, here’s a code snippet with both HTML and plain text:

const mailOptions = {
  from: 'you@example.com',
  to: 'friend@example.com',
  subject: 'Welcome to our service',
  text: 'Welcome onboard!',  // plain text version
  html: '<h1>Welcome!</h1><p>We are excited to have you onboard.</p>'
};

In the above snippet, the html content will be used as the email body for clients that can display HTML, while the text serves as a fallback. You can use any HTML tags, inline CSS (though support varies by email client), and even include dynamic content or templates

Send email with attachment

To send attachments (files like PDFs, images, etc.) with Nodemailer, you can add an attachments array in the mail options. Each attachment can be specified with properties like filename and either a path to the file or raw content. Additionally, Nodemailer is quite flexible: you can attach files from disk, streams, buffers, or even data URLs.

For example, suppose you want to attach a PDF invoice stored on disk:

const mailOptions = {
  ... // (other fields like from, to, etc.)
  subject: 'Your invoice',
  text: 'Please find your invoice attached.',
  attachments: [
    {
      filename: 'invoice.pdf',
      path: '/path/to/invoice.pdf' // path to file on your server
    }
  ]
};

When Nodemailer sends this email, it will read the file at the given path and include it as an attachment. You can specify multiple objects in the attachments array to send more than one file. Instead of path, you could use content to provide file data (for example, a Buffer or base64 string) and even specify a contentType if needed.

To display an image within the HTML of the email (inline image), you can use a special case of attachments: set the attachment’s cid (content ID) and refer to that cid in your HTML <img src="cid:..."> tag. This way, the image is embedded in the email content rather than just attached.

Send email to multiple recipients

Nodemailer makes it simple to send an email to multiple recipients with:

  • Multiple addresses in to: Provide a comma-separated list of email addresses as the to field (or an array of addresses). Nodemailer will send the email to all listed recipients.
  • CC and BCC: Use the cc and bcc fields in mailOptions to add additional recipients who should receive copies (carbon copy or blind carbon copy).

For example, to send the same email to two friends, you could change your mailOptions accordingly:

const mailOptions = {
  from: 'you@example.com',
  to: 'friend1@example.com, friend2@example.com',  // multiple recipients
  subject: 'Hello everyone',
  text: 'This email was sent to two people at once!'
};

Pro tip: If using CC or BCC, just add cc: ‘person@example.com‘ or bcc: ‘another@example.com‘ as needed. Keep in mind that recipients on the to and cc lines will see each other’s addresses, whereas bcc recipients are hidden from other recipients.

Send email in Bun.js using email API

Instead of managing SMTP connections and transport security yourself, you can use Mailtrap email API. This can simplify sending and often provides additional features (templating, analytics, bulk sending, etc.).

Again, let’s start with basic plain-text emails.

  • Import and initialize the Mailtrap client:

First, install the Mailtrap Node.js SDK in your Bun project:

bun install mailtrap

Then, import the MailtrapClient class from the Mailtrap package and create an instance with your API token:

import { MailtrapClient } from 'mailtrap';

const TOKEN = "<YOUR_API_TOKEN_HERE>";
const SENDER_EMAIL = "no-reply@yourdomain.com";
const RECIPIENT_EMAIL = "friend@example.com";

const client = new MailtrapClient({ token: TOKEN });

Important: Make sure to add your Mailtrap API key to <YOUR_API_TOKEN_HERE>.

With the code above, we initialize the Mailtrap client with our API token and define the sender and recipient email addresses for convenience. The sender email should be from the domain you verified with Mailtrap, and the recipient can be any valid email address.

  • Send an email using the client

The Mailtrap client provides a send() method. We pass an object describing our email (similar to mailOptions before). For a simple plain-text email, you can use the following snippet:

const sender = { name: "My App", email: SENDER_EMAIL };

client.send({
  from: sender,
  to: [ { email: RECIPIENT_EMAIL } ],
  subject: "Hello from Bun.js and Mailtrap!",
  text: "This is a test email sent through the Mailtrap Email API."
})
.then(response => console.log("Mailtrap API response:", response))
.catch(error => console.error("Error sending email via API:", error));

Code breakdown:

  • We constructed a sender object with a name and email. The from field in the email uses this object.
  • The to field is an array of recipient objects. Each recipient can include an email and, optionally a name. In our case we send to one recipient, but you can add multiple objects to send to many recipients (see next sections).
  • We provide a subject and a text content for the email. This is analogous to Nodemailer’s options.
  • The send() method returns a Promise, so we chain .then and .catch to handle success or error. On success, you’ll get a response object (for example, with an ID of the sent message and info), and on failure, an error explaining what went wrong.

And that’s it,  no direct SMTP handling in your code. The Mailtrap client takes your request and communicates with Mailtrap’s email API for you.

Important: The first time you use Mailtrap’s Email API (or SMTP) in production, your sending domain must be verified and DNS records set up as per Mailtrap’s instructions; otherwise, the API will refuse to send.

For your convenience, here is the complete index.ts code for plain-text email sending:

import { MailtrapClient } from "mailtrap";

const TOKEN = "<YOUR_API_TOKEN_HERE>";
const SENDER_EMAIL = "no-reply@yourdomain.com";
const RECIPIENT_EMAIL = "friend@example.com";

const client = new MailtrapClient({ token: TOKEN });

const sender = { name: "My App", email: SENDER_EMAIL };

client
  .send({
    from: sender,
    to: [{ email: RECIPIENT_EMAIL }],
    subject: "Hello from Bun.js and Mailtrap!",
    text: "This is a test email sent through the Mailtrap Email API.",
  })
  .then((response) => console.log("Mailtrap API response:", response))
  .catch((error) => console.error("Error sending email via API:", error));

To run the code, again, you can use bun run index.ts.

Send HTML email

Sending an HTML email via the Mailtrap API is straightforward as well. Instead of a text field (or in addition to it), you provide an html field in the payload. You can also include other metadata like categories or custom variables, which Mailtrap supports for tracking and templates

Here’s an example of sending an HTML email using the Mailtrap client (you can update your code according to it:

client.send({
  from: { name: "My App", email: SENDER_EMAIL },
  to: [ { email: RECIPIENT_EMAIL } ],
  subject: "Welcome to My App!",
  html: `
    <!doctype html>
    <html>
      <head>
        <meta charset="UTF-8">
      </head>
      <body style="font-family: sans-serif;">
        <div style="max-width: 600px; margin: auto;">
          <h1 style="font-size: 18px;">🎉 Welcome to My App!</h1>
          <p>We're excited to have you on board. This is a <b>HTML email</b> sent with Bun.js.</p>
          <p>Now you can send emails using Mailtrap's API and Bun runtime easily.</p>
        </div>
      </body>
    </html>
  `
})

In this snippet, we build a simple HTML document with inline styles and use it as the email body. The Mailtrap API will send this content as HTML part of the email. You can include images, links, and typical HTML content, just remember not all HTML/CSS translates perfectly to email (use tables or inline CSS for complex layouts, and avoid external CSS). 

Send email with attachment

With the Mailtrap client, you include an attachments array in the send() payload. Each attachment can have a filename, the file data as content (in binary or base64 form), and optionally a disposition (e.g., “attachment” for a normal attachment or “inline” for embedded images). 

For instance, if you have a PDF file’s content in memory (say you read a file or generated it on the fly as a Buffer), you could send it like so:

import { readFileSync } from "fs";

const reportPdfBuffer = readFileSync("./invoice.pdf");

client.send({
  from: { name: "Reports", email: SENDER_EMAIL },
  to: [ { email: RECIPIENT_EMAIL } ],
  subject: "Your requested report",
  text: "Please find the report attached.",
  attachments: [
    {
      filename: "report.pdf",
      content: reportPdfBuffer,       // the binary content of the PDF
      disposition: "attachment"       // ensures it's a downloadable attachment
    }
  ]
});

In the above, reportPdfBuffer is a Buffer or binary string containing the file data. The Mailtrap API will handle encoding this and delivering it as an attachment. We set disposition: "attachment" to indicate it’s an attachment (not to be displayed inline in the email body). 

Tip: You can attach multiple files by adding multiple objects in the attachments list.

Send email to multiple recipients

With the Mailtrap API client, sending to multiple recipients is just a matter of providing multiple entries in the to array. For example:

client.send({
  from: { name: "Alerts", email: SENDER_EMAIL },
  to: [
    { email: "user1@example.com", name: "User One" },
    { email: "user2@example.com", name: "User Two" },
    { email: "user3@example.com", name: "User Three" }
  ],
  subject: "System Maintenance Notification",
  text: "Dear users, we'll have a scheduled maintenance at midnight."
});

This code will send one email to each of the three recipients listed. Each recipient will get their own copy of the email. Unlike listing addresses in a single string (as we did with Nodemailer), here we provide an array of objects. This allows you to include names and other metadata per recipient. 

Mailtrap email API also supports CC and BCC. The client’s send method accepts cc and bcc fields, which would be arrays of recipient objects just like to. For example, you could add:

cc: [ { email: "manager@example.com", name: "Manager" } ],
bcc: [ { email: "audit@example.com" } ],

Note on bulk emails: If you need to send a bulk email (a large number of recipients, like a newsletter blast), Mailtrap’s API has specialized endpoints/streams for bulk sending. You might not want to list thousands of addresses in one API call. Instead, you’d use their bulk send capability or send in batches. But for up to dozens of recipients, adding them in the to (and cc, bcc) fields is fine.

Wrapping up

That’s it for our ‘bun.js send email tutorial’!

To summarize: If you want a straightforward but minimalistic solution to send emails from Bun.js, use Nodemailer + Mailtrap SMTP. To automate your sending and use features like templates, webhooks, or even contact management, use Mailtrap Email API.

Also, be sure to check out our blog, where you can learn how to send emails in:

]]>
SMTP vs Email API Explained & Compared: Find Out What Method Developers Should Use https://mailtrap.io/blog/smtp-vs-email-api/ Fri, 01 Aug 2025 10:46:26 +0000 https://blog.mailtrap.io/?p=1798 A vinyl record and Spotify both get your favorite jams playing, but the way they do it couldn’t be 

more different. The same applies to SMTP and email API when it comes to sending emails.

SMTP is the underlying protocol that has powered email for decades, while an API is an interface designed to interact with that protocol in a faster, more flexible, developer-friendly way.

In this article, we’ll break down SMTP vs email API – how each works, explore their advantages and limitations, and see which approach is more efficient for your email-sending needs.

SMTP vs email API: a snapshot

SMTP is best for straightforward email sending without requiring complex programmatic control over advanced features. Ideal for systems that send emails like password resets or notifications, as well as legacy platforms. Jump to SMTP →

Email API is designed for modern, scalable applications that require speed and advanced capabilities such as real-time tracking, detailed reporting, and dynamic templates. It works well for high-volume sending, complex transactional messages, and automated workflows. Jump to Email API →

Feature / AspectSMTP (Method)Email API (Interface to Service)
Primary Use CaseSimple email relay, basic notifications, legacy systemsTransactional emails, email marketing campaigns, high-volume automated sending
SetupRequires SMTP credentials (host, port, username, password)Requires API key and integration with provider
SpeedSlower; step-based message transferFaster; optimized for bulk email and real-time sending
ScalabilityLimited for large volumesScales easily for millions of emails
FeaturesBasic delivery onlyAdvanced: tracking, reporting, templates, personalization

What is SMTP?

SMTP, short for Simple Mail Transfer Protocol, is the standard protocol used to send emails from one email server to another. It’s been around since the early days of the internet and remains the backbone of email delivery today. 

In practice, you’ll often hear the term “SMTP relay”, which generally refers to a third-party service that routes outgoing emails on behalf of your application. Technically, SMTP itself is just the protocol, not the service. However, the term SMTP relay service has become so widely used in the industry that many providers use it interchangeably when talking about sending email through their servers.

The SMTP protocol works by using a series of text-based commands to transfer email messages from a sender’s mail server to the recipient’s server.

So, for example, a typical SMTP session would include commands like:

  • HELO or EHLO – to introduce the client to the server
  • MAIL FROM:<sender@example.com> – to specify the sender’s address
  • RCPT TO:<recipient@example.com> – to define the recipient
  • DATA – to send the email body and headers

Each of the above commands gets a response from the server. This creates a back-and-forth conversation until the message is successfully delivered.

To put this into context, here’s a practical example of sending an email with SMTP in Python using Mailtrap:

import smtplib

sender = "Private Person <hello@test.com>"
receiver = "A Test User <dzenana.kajtaz@railsware.com>"

message = f"""\
Subject: Hi Mailtrap
To: {receiver}
From: {sender}

This is a test e-mail message."""

with smtplib.SMTP("live.smtp.mailtrap.io", 587) as server:
    server.starttls()
    server.login("api", "<YOUR_API_TOKEN>")
    server.sendmail(sender, receiver, message)

Pros of SMTP

Alright, so I’ve covered what SMTP is and how it works. Now, let’s talk about why this decades-old protocol is still relevant in today’s API-driven world. These are the most common reasons teams continue to choose SMTP:

Universal compatibility – Almost every email client, application, and server supports SMTP, meaning you can integrate it into virtually any system without compatibility issues.

Simplicity in setup – Getting started with SMTP is straightforward. All you need are your SMTP credentials (host, port, username, and password), and you’re ready to send emails – no complex coding required.

Proven and reliable standard – SMTP has been around for decades, making it stable, predictable, and well-documented. It works consistently across providers without unexpected surprises.

Works with legacy systems – Older applications and platforms often rely on SMTP as their default email protocol, making it the easiest and most compatible choice for integration without major rewrites.

Broad language and framework support – SMTP libraries are available for virtually every programming language, ensuring smooth integration no matter your tech stack.

Vendor independence – Because SMTP is an open standard, users are not locked into any single provider. Switching typically only requires updating credentials, not rewriting your integration.

Supported by most tools and plugins – Popular CMS platforms like WordPress and Joomla, along with form plugins and e-commerce extensions, often provide built-in SMTP support for quick email configuration.

Cons of SMTP

So, it’s clear that SMTP does its job well for basic sending. But as email needs grow more complex, SMTP’s limitations can become evident. Here’s where SMTP struggles the most:

Slower performance for large volumes – SMTP processes each email through multiple sequential commands. This makes it inherently slower, especially compared to APIs optimized for bulk transmission.

Limited scalability – SMTP wasn’t designed for massive email workloads or real-time delivery. Handling high volumes often means managing multiple simultaneous connections and IP pools, which increases complexity and the risk of throttling.

Feature-light by default – Beyond basic delivery, SMTP offers no built-in tools for analytics, reporting, or template management. Adding these features requires additional email infrastructure or third-party solutions.

Vague error handling – SMTP error response codes (like 550 or 421) can be cryptic and inconsistent across providers. This lack of clarity makes diagnosing issues slow and often requires digging through obscure documentation.

Security risks if misconfigured – While SMTP supports TLS, it’s not always enforced by default. Without proper setup, sensitive data and credentials can be transmitted in plaintext, creating compliance and security gaps.

Not cloud-native – SMTP’s design lacks the flexibility needed for microservices and distributed systems. This makes it struggle to adapt to modern containerized or serverless environments without extra configuration.

When to use SMTP

Now that we’ve weighed the strengths and weaknesses of SMTP, the question is: when does it still make sense to use this tried-and-true protocol instead of switching to an API?

Below are some scenarios where SMTP continues to make the most sense:

You’re integrating with a CMS or low-code tool

If your team is using platforms like WordPress, Drupal, or Joomla, or working with popular plugins and form builders, SMTP is often the default method for email delivery. It requires no custom coding – just paste your SMTP credentials into it and start sending. For marketers or non-technical users managing websites, this low-friction setup is a big win.

You’re supporting legacy applications or infrastructure

Older business systems like ERP platforms, internal tools, or CRMs written in languages like COBOL, VB, or older versions of Java, often lack native support for HTTP APIs. Since SMTP is a universally accepted standard, it allows these systems to send emails without a major rewrite, making it the go-to solution for environments that prioritize stability over modern architecture.

Your sending volume is small and predictable

If you’re sending a few hundred emails per day, such as password resets, signup confirmations, or support replies, SMTP handles it with ease. In these cases, you don’t need the scalability or advanced features of an API. SMTP gives you a reliable channel without adding architectural complexity or overhead.

What is an email API?

An Email API (Application Programming Interface) is a modern way to send emails by making HTTP (hypertext transfer protocol) requests to an endpoint of an email service provider. This approach offers speed, flexibility, and advanced functionality that traditional protocols like SMTP don’t offer.

When getting familiar with email APIs, you might also hear the term SMTP API. But, despite their name, SMTP APIs typically don’t replace SMTP itself. Instead, they provide an interface to manage or send emails through an SMTP service. Still, some providers and users treat “SMTP API” and “email API” as the same thing. This, in practice, is incorrect as email APIs are designed for full-featured integrations, not just for routing through SMTP.

During the process of sending emails through an API, your application interacts with the email provider over HTTPS using requests rather than exchanging a series of text-based commands. The structured HTTP requests (usually in JSON) include all the necessary details such as, recipient addresses, subject line, message body, and optional parameters like tracking or templates.

Here are the steps a typical email delivery process via API consists of:

  • Authenticate using an API token provided by the email service.
  • Send an HTTP request (usually POST) to the provider’s endpoint with email details in JSON format.
  • Include additional parameters like HTML email content, templates, tracking options, or attachments if needed.
  • Receive a response with a status code and detailed delivery info—something SMTP can’t provide out of the box.

A workflow of this type is optimized for delivery speed and scalability and integrates easily into modern applications through official SDKs and libraries.

With Mailtrap’s Python SDK, you can send an email through an email API using the following code:

import mailtrap as mt

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

# Initialize client and send email
client = mt.MailtrapClient(token="your-api-key")
client.send(mail)

Pros of email API

So we’ve established that email APIs aren’t just an upgrade; they’re a complete shift in how email delivery works for modern apps. Now, let’s break down some of the pros they bring to developers and businesses:

Speed and efficiency – API requests are lightweight and optimized for high-volume sending, making them significantly faster than SMTP’s step-by-step handshake process.

Feature-rich by design – APIs unlock advanced capabilities like open and click tracking, detailed reporting, dynamic templates, attachments, and even A/B testing, all built into the integration, without extra layers.

Better error handling – Instead of decoding vague SMTP error codes, APIs return structured, human-readable responses, making troubleshooting faster and easier for developers.

Scalability for modern workloads – APIs handle large volumes effortlessly without requiring multiple connections. They’re designed for massive sending, real-time triggers, and automated workflows.

Seamless integration with modern architectures – APIs fit naturally into microservices, mobile apps, and serverless environments. Most providers also offer SDKs for popular programming languages, speeding up development and reducing friction.

Fewer firewall complications – Unlike SMTP, which often requires opening SMTP ports (like 25, 465, or 587) and configuring firewall exceptions, Email APIs communicate over HTTPS (port 443), which is almost always allowed by default. This simplifies deployment and reduces network-related headaches.

Advanced automation support – APIs make it simple to build event-driven or lifecycle-triggered emails directly into your application logic, something SMTP was never designed for.

Cons of Email API

Speed, flexibility, and other advantages that email APIs bring also come with some trade-offs. So, before making the switch, consider these potential drawbacks:

Higher integration complexity – Unlike SMTP, which works almost anywhere with just credentials, APIs require coding, and familiarity with the provider’s documentation. This can slow initial setup, especially for teams without strong dev resources.

Vendor dependency – APIs are provider-specific, so switching services often means rewriting parts of your codebase. Even with SDKs and REST standards, there’s more lock-in than with SMTP’s universal protocol.

Potential cost overhead – For basic use cases, an API can feel like overkill. And if you’re sending just a few password resets or low-volume notifications, the extra development effort (and sometimes pricing structure) might outweigh the benefits.

Learning curve for advanced features – While APIs offer power and flexibility, taking full advantage often requires developers to understand advanced parameters, authentication methods, and integration nuances. This can lead to longer onboarding times and a higher dependency on technical resources.

Security and compliance complexity – APIs often provide more features, but with that comes a bigger responsibility for securing API keys, handling rate limits to prevent abuse, and ensuring compliance with frameworks like GDPR or HIPAA when processing more personal data for tracking and analytics. 

When to use email API

Understanding what an Email API can do is one thing. Deciding when it’s worth implementing is another. Below are the real-world use cases where APIs outshine SMTP and give you the performance, control, and flexibility you need.

You’re scaling rapidly and need elasticity

If your platform expects sudden spikes, like e-commerce sales during holidays, SaaS onboarding surges, or viral user growth, APIs make it easy to send hundreds of thousands or even millions of emails without downtime. Unlike SMTP, which requires multiple connections and IP juggling, APIs scale natively through lightweight HTTP requests and parallel processing, ensuring emails don’t get delayed when demand peaks.

You need actionable insights to optimize performance

For businesses that rely on metrics to refine email campaigns or improve user engagement, APIs offer built-in tracking for opens, clicks, bounces, and even device data. These insights go far beyond basic delivery reports and allow marketing and product teams to make data-driven decisions, run A/B tests, and personalize follow-ups, all without additional tooling or manual effort.

Your workflows are event-driven

If your application triggers emails based on real-time events – think onboarding emails after signup, payment confirmations after a transaction, or security alerts for suspicious logins – APIs integrate seamlessly into your codebase. Also, instead of relying on batch jobs or manual processes, APIs allow instant email dispatch tied to system events, improving user experience and operational efficiency.

Your application is cloud-native

If you’re building on modern infrastructure (microservices, serverless environments, or mobile-first architectures), APIs fit naturally into your tech stack. They work with CI/CD pipelines, containerized apps, and API gateways without needing the extra configuration SMTP often requires, making deployment faster and easier.

Your priority is personalization at scale

If your product strategy depends on hyper-personalized messaging, like dynamic templates, behavioral segmentation, and real-time content updates, APIs handle these requirements natively. They support dynamic variables and logic within the email payload, eliminating the need for complex workarounds that SMTP-based setups often require.

Email service providers with SMTP and email API

After running through all these aspects of the two most popular sending methods, you might be ready to implement SMTP or Email API for sending emails. So, your next step is choosing the right provider. 

Below, I’ll provide an overview of three widely used solutions that offer both methods.

But before we get into that, here’s a side-by-side comparison of email APIs across popular platforms:

ProviderDedicated IPsSeparate StreamsRate HandlingSDKsWebhooksTemplates
MailtrapFrom 100k emails/month, auto warm-up✅ Bulk + transactional✅ No limits, customizable throttlingNode.js, PHP, Ruby, Python, Elixir, Java✅ Full events + logs✅ Handlebars
ResendAdd-on from 500 emails/day, auto warm-up✅ No details on throttlingNode.js, PHP, Laravel, Python, Ruby, Go, Java, Rust, .NET✅ Limited, domain-focused❌ Manual
PostmarkAdd-on from 300k emails/month✅ Transactional + broadcast✅ No limits, auto throttlingRuby, RoR, .NET, Java, PHP, Node.js✅ Standard events✅ Mustachio
MailgunFrom 50k emails/month (add-on), included from 100k✅ Yes, limit not specifiedPython, Go, Node.js, PHP, Java, Ruby✅ Full events✅ Handlebars + versioning
SendGridAvailable from 100k emails/month✅ 10,000 r/s, 1,000 recipients/emailC#, Go, Java, Node.js, PHP, Python, Ruby✅ Full events + logs✅ Handlebars + versioning

Want to read the full rundown? Click 👉here for our guide on Email API flexibility.

Mailtrap Email Delivery Platform

This is an image showing Mailtrap's new landing page

Ratings:

  • G2: 4.8/5
  • Capterra: 4.8/5

Mailtrap is an Email Delivery Platform designed for product companies with high sending volumes. The platform offers a RESTful API and SMTP with high email deliverability and supports senders with growth-focused features, as well as industry best analytics for analyzing and monitoring performance. With Mailtrap you can deliver user-triggered, mass, and marketing emails reliably while also scaling with ease as your sending needs grow. 

Documentation:

SDKs & code snippets:

Key features:

  • Email API
  • SMTP service
  • Bulk stream 
  • Industry-best analytics
  • Email Sandbox
  • Up to 30 days of email logs
  • 24/7 expert support

Mailgun

This is an image showing Mailgun's landing page

Ratings:

  • G2: 4.2/5
  • Capterra: 4.3/5

Mailgun is a reliable email delivery service built for businesses and developers that need both SMTP and API-based email sending. It supports transactional and marketing emails at scale and includes tools for IP warm-up, deliverability monitoring, and basic analytics. Mailgun is well-suited for teams that want flexibility and control, though it may require more setup compared to some streamlined solutions.

Documentation:

SDKs & code snippets:

Key features:

  • Email API
  • SMTP service
  • Email validation service
  • Basic analytics and log retention

Resend

This is an image showing Resend's landing page

G2 Rating: 4.3/5

Capterra Rating: Not yet listed 

Resend is a lightweight SMTP and email API platform focused on simplicity and ease of integration. It’s a good option for teams that need straightforward transactional email delivery without a lot of extra features. Resend mostly offers a developer-friendly experience and quick setup for small-scale or fast-moving projects.

Documentation:

SDKs & Code Snippets:

Key Features:

  • Email API
  • SMTP service
  • Webhooks for delivery events and bounces
  • Email logs for recent messages

Wrapping up

Choosing between SMTP and Email API comes down to your priorities. If simplicity and universal compatibility are what you need, SMTP is still a reliable choice. It’s easy to configure, works with almost any system, and is perfect for low-volume or basic sending scenarios.

But if you’re building for scale, speed, and advanced functionality, an Email API is hard to beat. With features like tracking, personalization, analytics, and better error handling, APIs provide the flexibility modern applications demand.

Still, it’s worth noting that it’s not always a SMTP vs email API decision. Many teams start with SMTP for quick integration and later move to APIs as their email requirements grow.

With Mailtrap, you get a platform that supports big email senders as well as those that are just starting to plan their scaling journey with its RESTful email API and SMTP. Ready to get started?

For more content on email APIs and SMTP, check out our other articles:

]]>
5 Best Email API Services For Developers Tested & Compared: Here’s What I Found https://mailtrap.io/blog/best-email-api/ Mon, 28 Jul 2025 16:37:54 +0000 https://mailtrap.io/?p=25129 Considering the size of the industry nowadays, I have to say that looking for the best email API (application programming interface) is like searching for a needle in a haystack.

So, I’ve spent the past few weeks going through the haystack of email APIs, then I reviewed the best of them and compiled a nice little list to help you choose the best one for your needs.

Before we dive in, if you feel like freshening up or fine-tuning your knowledge, you can check out the article our email infrastructure expert, Dzenana, has written on email APIs.

Best email API: a snapshot

Click on a platform name to jump ahead to the detailed review.

  • Mailtrap is best for high-volume product companies that are looking for high deliverability rates, in-depth analytics, and growth-focused features.
  • Mailgun is best for developers with in-depth email sending expertise who need detailed logs and an email validation API on top of an email API.
  • SendGrid is best for enterprise users who need granular control over their user permissions.
  • Amazon SES is best for current AWS users who have extensive experience with setting up, configuring, and supporting email infrastructures.
  • Postmark is best for teams looking to send transactional emails and don’t need any extra features.

I’ve made a chart to help you compare the APIs you might be leaning towards. Check it out.

Email APIFree planPricingIntegration
Mailtrap3,500 per monthFrom $15Node.js, PHP, Ruby, Python, Elixir, Java
Mailgun100 per dayFrom $15Python, Go, Node.js, PHP, Java, Ruby
SendGrid100 per dayFrom $19.95C#, Go, Java, Node.js, PHP, Python, Ruby
Amazon SES3,000 per month (during the first year)$0.10 per 1,000 emailsJava, .NET, PHP, Python, Ruby, Go
PostmarkN/AFrom $15Ruby, RoR, .NET, Java, PHP, Node.js

Disclaimer: The ratings, features, and prices are up-to-date as of writing this article, but they could be different when you’re reading it, as they’re prone to change.

Email API providers comparison methodology

To bring you an unbiased, accurate, and comprehensive review of the best email API providers, I conducted a thorough research and tested (almost) everything they offer.

However, I must note that I didn’t conduct the research alone, since I had the help of Mailtrap deliverability experts, security team, and developers who work on our infrastructure.

Documentation research

First and foremost, I made sure to dig through each provider’s:

  • Official API docs to see how easy to integrate for your team an API is and what it offers (e.g., sending endpoints, bounce handling, templates, etc.).
  • GitHub repositories to check whether an API is being regularly maintained and updated.
  • Testimonials and reviews to see what a provider’s user base thinks and how the APIs hold up compared to advertisements. 
  • Knowledge bases and blogs to look for helpful guides and tutorials on setting up and using an API.

Hands-on testing

Recently, over at Mailtrap, we conducted a thorough email API flexibility research where we:

  • Sent emails with different sending configurations to test real-world use cases such as sending attachments and bulk emails, etc.
  • Triggered API rate limits and retry behavior to inspect how an API handles high volume, throttling, and retries.
  • Created email templates to evaluate how much personalization each API allows and to test templating logic and dynamic content.
  • Set up webhooks for some of the events they support to see how quickly you get automated notifications about the most important metrics like bounces.

Now, let’s get on with the reviews of each email API provider or check out the detailed criteria first by clicking on this jump link

Best email API for high deliverability & flexibility: Mailtrap

G2: 4.8 🌟 Capterra: 4.8 🌟

Mailtrap Email Delivery Platform is designed for developer and product teams with high sending volumes that need high deliverability rates, in-depth analytics, and growth-focused features. 

Additionally, Mailtrap offers one of the most flexible email APIs out there that allows developer teams to fine-tune their sending configuration according to their specific needs. Of course, I would never claim this without being able to back it up.

Recently, we’ve performed numerous tests with the top APIs in the industry, simulating real-world usage to see how much control the user gets. Here’s a table that summarizes key findings of our research:

Dedicated IPsAvailable from 100k emails/month with auto warm-up. 
Separate streams✅ Bulk and transactional
Rate handling✅ No limits, customizable throttling
Webhooks✅ Full events + logs
Templates✅ Handlebars
Customer supportTicket, chat, priority support

To learn more about our methodology and get more in-depth information on technical tidbits like IP infrastructure, throttling, retry mechanisms, etc., read our full comparison

Why is it the best email API?

  • High deliverability

Mailtrap uses separate sending streams, dedicated IP addresses, email warm-up, throttling, and other advanced features to help all of its users achieve high deliverability rates, regardless of the plan. 

The platform also has a team of deliverability experts at its users’ disposal, who can help you with any deliverability-related issues you might face.

Moreover, we’ve recently performed several deliverability tests with top API providers. To make sure the tests were fair to everyone, we used free plans, didn’t warm up domains, used the same template, etc. 

Here’s how Mailtrap performed:

PlatformEmail placement resultsSpam filter ratingInbox email delivery with top providers
MailtrapInbox: 78.8%
Tabs: 4.8%
Spam: 14.4%
Missing: 2.0%
Google Spam Filter: Not spam; Not phishy
Barracuda: Score 0
Spam Assassin: Score: -3.8
Gmail: 67.50%
Outlook: 77.78%
Hotmail: 100%
Yahoo: 55.56%
Source
  • In-depth analytics

With Mailtrap, you can keep an eye on the performance of your email campaigns thanks to helicopter view dashboards and drill-down reports. These let you track email metrics like opens, clicks, bounces, and others. 

Additionally, Mailtrap will keep your email logs for up to 30 days,

  • Email templates

Besides the drag-and-drop email builder, which can make your marketers’ lives easier, Mailtrap offers an HTML editor your devs can use to create email templates from scratch.

The templates use the Handlebars engine with which you can set up additional variables and conditional variables like if and else statements to automate a big portion of your sending workflow.

Pricing

Mailtrap offers several different scalable plans and has one of the most cost-effective email APIs since it doesn’t keep customer support or high inboxing rates locked away for higher tiers.

As of writing this article, the most popular plan is Business 100k, being in the golden middle and offering a plethora of advanced features with 100,000 monthly emails at an affordable rate.  

Here’s a quick table that sums the pricing plans up:

PlanMonthly costEmail limitKey features
Free $0Up to 3,500 emailsSMTP relay,
SMTP API,
drag-and-drop editor,
webhooks
Basic From $1510,000+ emailsEmail logs (5 days),
body retention,
click-rate tracking,
HTTPS link branding
Business (the most popular)From $85100,000+ emailsEmail logs (15 days),
dedicated IP,
auto warm-up
Enterprise From $7501,500,000 emailsAll of the above +
priority support and 30 days email log retention
CustomCustomFrom 1,500,000All of the above

For more details, please consult the official Mailtrap pricing page.

Pros

Cons

  • Currently, you can only integrate Mailtrap with services such as Zapier and Tabular email, but more integrations are on the way.
  • Automations are still in alpha but the official release is planned for the near future.

Developer experience

Official API documentation

Mailtrap offers easy-to-use SDKs for Node.js, PHP, Ruby, Python, Elixir, and Java.

It offers code snippets for major programming languages, which lets you start sending emails right away. All you need to do is copy/paste the provided script into your sending configuration, insert your credentials, and you’re off.

Here’s a Node.js code snippet offered by Mailtrap:

const Nodemailer = require("nodemailer");
const { MailtrapTransport } = require("mailtrap");

const TOKEN = "<YOUR_API_TOKEN>";

const transport = Nodemailer.createTransport(
  MailtrapTransport({
    token: TOKEN,
  })
);

const sender = {
  address: "hello@demoatmailtrap.com",
  name: "Mailtrap Email",
};
const recipients = [
  "demo@mailtrap.io",
];

transport
  .sendMail({
    from: sender,
    to: recipients,
    subject: "You are awesome!",
    text: "Congrats for sending an email with Mailtrap!",
    category: "Integration",
  })
  .then(console.log, console.error);

The documentation is also quite extensive, regularly updated, and has everything you need in one place.

Additionally, Mailtrap has a blog with step-by-step articles on setting up the platform’s SMTP/API and sandbox with all major programming languages and web dev frameworks, such as:

On top of that, their YouTube team has been busy and provided a lot of follow-along videos on setting up sending functionality, validation mechanisms, and more. Check it out.

Security 

From email authentication to detailed logs and monthly DKIM key rotation, Mailtrap has every security element covered:

Encryption & transmission securityStrong TLS enforcement, MTA-STS support
Authentication & identity controlSPF, DKIM, DMARC alignment
API & credentials securityGranular API keys, IP whitelisting
Account access & user controlsMFA, RBAC, detailed audit logs
Abuse prevention & misuse protectionRobust reputation management, real-time
security monitoring
Security event logging & notificationsDetailed logs, customizable alerts

Compliance

Mailtrap is compliant with all modern regulations, it’s ISO certified, and SOC 2 certification is in progress:

GDPR✅ Compliant
Data residency Based in EU but the servers are in the US
SOC 2, ISO 27001, HIPAA✅ 
User rights supportDSAR support & data deletion upon request
LoggingDetailed logs, exportable
DPA✅ Available on request

Testimonials

While scouring online reviews, I’ve noticed that Mailtrap is praised for its deliverability and dev-friendly API. One of the reviewers also mentioned how the Mailtrap support team helped them resolve DKIM alignment issues within a few hours:

Source: G2

Others like its API for its reliability and rapid delivery time:

Source: Capterra

Best for advanced email devs: Mailgun

G2: 4.2 🌟 Capterra: 4.3 🌟

Mailgun is a transactional email service that provides an SMTP and email API designed for developers. 

Here’s a quick breakdown of its most important features:

Dedicated IPsAvailable from 50k emails/month as an add-on and included from 100k emails/month.
Separate streams
Rate handling✅ Yes, limit not specified
Webhooks✅ Full events
Templates✅ Handlebars + versioning
Customer supportTicket, chat, and phone

Why is it the best for advanced email devs?

  • Webhook API

Mailgun’s webhook API can be supported at the domain level, which can be handy if you’re using multiple domains. Additionally, it supports many engagement events, such as accepted, delivered, spam complaints, and more.

If a webhook delivery fails, Mailgun will retry the delivery for up to 8 hours.

  • Email validation API

If you want to add email validation logic to your web forms, you can do so with Mailgun’s email validation API. Besides the basic syntax and DNS checks, Mailgun cross-references your email list against its database of 450 billion emails, and warns you about high-risk addresses.

You can also validate your contacts in bulk if you don’t feel like integrating.

  • Detailed email logs

Mailgun keeps your email logs for up to 30 days, but that’s not their biggest selling point. Namely, what makes them great is the fact that there are 10 filter fields you can use to customize your logs and then analyze them across all your domains.

These include TO and FROM headers, event types, list names, tag names, and others.

Source: Mailgun

Pricing

Mailgun has a generous free tier that lets you send 5,000 emails during the first month, which would make it perfect for startups if it didn’t lock away some important features like dedicated IPs to high-tier plans. Nonetheless, here’s a brief summary of its pricing:

PlanMonthly costEmail limitKey features
Free$0100 per dayEmail API and SMTP, 
1 custom sending domain,
2 API keys
1 day log retention
1 inbound route
BasicFrom $1510,000+Email API and SMTP, 
1 custom sending domain,
2 API keys
1 day log retention
FoundationFrom $3550,000+1,000 custom sending domains,
Email template builder and API,
5 days log retention,
ScaleFrom $90100,000+SAML SSO,
5,000 email validations,
Dedicated IP pools,
30 days log retention

For more details, please consult the official Mailgun pricing page.

Pros

  • High throughput
  • EU and US data centers
  • Rapid Fire Delivery SLA
  • Email validation
  • Onboarding support
  • Real-time tracking
  • Solid webhooks
  • Inbound email processing

Cons

  • Only the highest-tier plan, Scale, offers 30 days of email logs.

Developer experience

Official API documentation

Mailgun supports Python, Go, Node.js, PHP, Java, and Ruby.

The email platform has a dedicated developer documentation page, which you can use to inspect any of its 4 APIs. The page layout is super clear, and navigating is a breeze, making it great even for junior developers. Night mode is also a big bonus.

The code snippets Mailgun provides aren’t as extensive as they come, but the platform has a nice blog where you can find some solutions to several programming languages. 

Security

Mailgun’s focus is on granular user permissions, has all encryption check boxes cleared, and is quite a secure API:

Encryption & transmission securityMandatory TLS, MTA-STS
Authentication & identity controlSPF, DKIM, DMARC
API & credentials securityManage API keys, IP restrictions
Account access & user controlsMFA, granular user permissions
Abuse prevention & misuse protectionSpam detection, bounce handling
Security event logging & notificationsDetailed event logs, webhooks for notifications

Compliance

Mailgun is compliant with GDPR, stores its data in the EU, and is compliant with all of the latest regulations. You can get more info on the compliance and security page or check out the summary table below:

GDPR✅ Compliant
Data residency EU region sending & storage
SOC 2, ISO 27001, HIPAA✅ 
User rights supportUser data deletion & subject access
LoggingLogging & audit trails
DPA✅ Available

Testimonials

Overall, although it has its issues, Mailgun has solid ratings on review websites. A reviewer that stood out to me praised Mailgun’s API and the email platform’s ability to help their company comply with inbox provider policies for Google, Microsoft, and Yahoo:

Source: G2

I also found a short case study, describing how a Ruby-based company, DNSimple, used HTTParty to integrate with Mailgun API, then programmatically created and configured domains, set up forwarding routes based on regex, and more.

Best for enterprises: SendGrid

G2: 4.0 🌟 Capterra: 4.2 🌟

SendGrid is one of the oldest names in the industry, providing an email API and SMTP service most suitable for enterprises due its high level of multitenancy support.

Although it doesn’t offer a separate sending stream, SendGrid’s API is overall flexible:

Dedicated IPsAvailable from 100k emails/month.
Separate streams
Rate handling✅ 10,000 r/s, 1,000 recipients/email
Webhooks✅ Full events + logs
Templates✅ Handlebars + versioning
Customer supportTicket, chat, and phone

If you’re interested, check out how SendGrid compares to Mailtrap.

Why is it the best for enterprises?

  • Subuser accounts

If you own a multi-brand business, or an agency that has different clients, or if you simply need granular permission control, SendGrid lets you segment your sending and email API activity.

Namely, you can create subusers with specific permissions, give each user credit limits, etc. For example, you can set it up so that one user can only send transactional emails while another can send only bulk.

Most importantly, each subuser will have separate API credentials, stats, and sender reputation.

  • IP pool management

With SendGrid, you can assign dedicated IPs to different email types or group them together for better deliverability and sender reputation. 

Additionally, SendGrid offers IP Access Management, a strong security feature that lets you control who can access your account based on their IP address. 

  • Deliverability features

To help you ensure your emails land in main inboxes, SendGrid uses a cloud-based infrastructure and offers everything from warmed up geo-specific IPs to reputation monitoring and adaptive throttling and optimization.

You can also use SendGrid’s Deliverability Insights with its email API and webhooks to receive real-time notifications on key performance metrics.

Source: SendGrid

Pricing

SendGrid has straightforward pricing plans, although they can ramp up in cost if you intend to use the platform’s advanced features like dedicated IPs or have extra slots for teammates:

PlanMonthly costEmail limitKey features
EssentialsFrom $19.9550kAnalytics and deliverability insights,
Email API
Limited webhooks,
1 additional teammate
ProFrom $89.95100k All of the above
+Dedicated IPs, Validation API,
Reverse DNS,
1,000 additional teammates
PremierCustomCustomAll of the above + more

For more details, please consult the official SendGrid pricing page.

Pros

  • Pre-warmed up, geo-specific IPs
  • Quality of life features
  • Good documentation
  • Granular user control
  • Onboarding assistance
  • Long webhook retry windows
  • SMS support via Twilio
  • CRM support and integrations with other useful platforms

Cons

  • Dedicated IPs and reverse DNS are available only to high-tier users.
  • Slightly steeper learning curve since it’s geared towards developers.

Developer experience

Official API documentation

SendGrid supports C#, Go, Java, Node.js, PHP, Python, and Ruby.

The platform’s API documentation is pretty clear and has everything you need, although I especially liked the onboarding guide, which you can follow step-by-step when integrating the API.

There are also code snippets for everything, so your developers will have to spend minimal time coding.

The platform’s customer support team is also available via ticket, chat, and phone, although it’s locked to higher-tier plans.

Security

Besides offering detailed IP access management, SendGrid covers all security bases: 

Encryption & transmission securityEnforced TLS, MTA-STS
Authentication & identity controlSPF, DKIM, DMARC
API & credentials securityScoped API keys, IP access management
Account access & user controlsMFA, RBAC, SSO
Abuse prevention & misuse protectionReal-time spam feedback, proactive monitoring
Security event logging & notificationsActivity feed, email event webhooks

Compliance

With SendGrid, you can choose whether you want to send your emails from EU or US, which allows you to deliver them faster. Besides that, it’s compliant with all of the important regulations:

GDPR✅ Compliant
Data residency EU region selectable, US default
SOC 2, ISO 27001, HIPAA✅ 
User rights supportSupports DSARs, deletion, data export
Loggingvia Twilio’s security tools
DPA✅ Available

Testimonials

Although I’ve noticed people aren’t big fans of SendGrid’s customer support on social media and ratings websites, they seem to be pretty satisfied with the email sending service API. More specifically, with how easy it is to integrate it:

Source: G2

However, I’ve noticed the opposite on Capterra, so you be the judge:

Source: Capterra

Best for AWS users: Amazon SES

G2: 4.3 🌟Capterra: 4.7 🌟

Amazon SES, short for Simple Email Service, is a cloud-based email API provider that’s geared towards developer teams who are already using AWS and have technical expertise.

As for the flexibility aspect of Amazon SES, here’s a summary table:

Dedicated IPsAvailable as an add-on (paid); managed or bring-your-own IPs
Separate streams
Rate handling✅ Customizable sending quotas, throttling with SES sending limits
Webhooks✅ Uses Amazon SNS for event notifications (deliveries, bounces, complaints)
Templates✅ Supports dynamic templates via the SES API or SMTP
Customer support✅ Ticket, chat, phone, email

Why is it the best for AWS users?

  • AWS integration

As part of the AWS Global Infrastructure, Amazon SES can be integrated with various AWS services. Some of these include S3, Lambda, SNS Support, and others.

Although this can streamline a lot of workflows, I must mention that it requires technical expertise. 

  • Identity and access management

With AWS Identity and Access Management (IAM), you can fine-tune your permissions based on users, roles, or systems. This allows you to manage your API key authentication and management, separate access between clients or environments, and more.

Source: Amazon SES
  • CloudWatch monitoring

Another useful AWS integration is Amazon CloudWatch. By integrating Amazon SES with it, you can get metrics on email sends, bounces, spam complaints, rejects, and rendering failures.

You can also create custom dashboards to visualize your email delivery performance or even set alarms to get notified when a certain metric exceeds a threshold (e.g., when your bounce rate goes above 5%).

Source: Amazon SES

Pricing

Amazon SES has a super simple pricing model: you pay $0.10 per 1,000 emails, which equals $1 for 10,000 emails or $10 for 100,000 emails.

Moreover, if you’re using Amazon EC2 and AWS Elastic Beanstalk, you get the first 62,000 emails for free.

For more details, please consult the official Amazon SES pricing page.

Pros

  • Integration with AWS
  • Super configurable
  • Secure and compliant
  • Strong and reputable IPs
  • A/B testing
  • Solid webhooks support
  • Has servers in EU, US, and Asia
  • Scalable and affordable pricing model

Cons

  • Doesn’t have an in-built native analytics UI, so you need to integrate with a 3rd party service instead.
  • Requires coding experience and being comfortable with the AWS ecosystem to be used to its 100%.

Developer experience

Official API documentation

Amazon SES has official libraries for Java, .NET, PHP, Python, Ruby, and Go.

Although Amazon SES has robust documentation, I have to note that you also need a little bit of developer experience, as well as experience with the AWS ecosystem. This is especially true if you want to use the API to its fullest potential.

For example, using Amazon SES API to send emails requires you to verify your domain, move out of the SES sandbox mode since all accounts start in it, create IAM credentials, configure permissions, and only then install an AWS SDK and set up your credentials. See what I mean?

Security

Being a part of the Amazon Infrastructure, it’s safe to say that you don’t have to worry when it comes to Amazon SES and security:

Encryption & transmission securityOpportunistic / forced TLS, MTA-STS (manual setup)
Authentication & identity controlSPF, DKIM, custom MAIL FROM, DMARC
API & credentials securityIAM policies, granular access control
Account access & user controlsIAM, MFA, CloudTrail integration
Abuse prevention & misuse protectionReputation dashboards, feedback loops
Security event logging & notificationsExtensive logs via CloudWatch/
CloudTrail

Compliance

Similarly, Amazon SES covers all bases when it comes to compliance, even offering servers in Asia:

GDPR✅ Compliant
Data residency Region-specific data storage (EU/US/Asia)
SOC 2, ISO 27001, HIPAA✅ 
User rights supportIAM-level controls & data export tools
LoggingCloudTrail logging
DPA✅ Through AWS DPA

Testimonials

One of the most common remarks I’ve seen about Amazon SES is that it’s affordable:

Source: G2

I’ve also found many reviews that say Amazon SES is for developer teams experienced with AWS configurations, although they don’t like the fact that you need 3rd party integrations for analytics:

Source: Capterra

Best for separate streams: Postmark

G2: 4.6 🌟 Capterra: 4.9 🌟

Postmark is an email platform that provides a transactional email API service for developers. 

It’s API is flexible, giving you room to play around with your infrastructure:

Dedicated IPsAvailable as an add-on from 300k emails/month
Separate streams✅Transactional and broadcast
Rate handling✅ No limits, auto throttling
Webhooks✅ Standard events
Templates✅ Mustachio
Customer supportTicket

Why is it the best for separate streams?

  • Separate sending streams

Postmark offers separate sending streams, similar to Mailtrap. The streams are dedicated to bulk emails (Broadcast Message Stream) and user-triggered emails (Transactional Message Stream).

Furthermore, you can create a custom stream for specific email types. So, for instance, you can create a separate stream for password reset emails, a separate one for invoices, etc.

  • Detailed event logs

With Postmark, you get to keep your email logs for up to 45 days, and they’re really detailed. 

You can filter the logs by status, subject, custom tags, and date. They’re also quite configurable. For example, you can configure them so you retrieve them automatically via Postmark’s Message API or even connect webhooks with them.

  • Transactional email templates

Welcome emails, receipts, invoices, user invitations, trial expirations; you name it. With Postmark Email Templates, you can create all kinds of designs for your app/project, and then send them when they’re ready via Postmark API.

The templates are powered by Mustachio, a lightweight templating engine that allows you to make dynamic email content

Source: Postmark

Pricing

Ever since its price increase in 2025, Postmark has been on the more expensive end, but nonetheless, it’s still more affordable than a lot of its competitors (looking at you, Mailchimp):

PlanMonthly costEmail limitKey features
Free$0100Email API,SMTP service,Core features likeemail templates, analytics, webhooks
BasicFrom $15,0010,000+Up to 4 users, SMTP & Rest API, Up to 5 servers and domains, Email templates
ProFrom $60,5050,000+Up to 6 users, Up to 30 streams, Up to 10 signature domains, All event webhooks, Stats & open/link,  tracking APIs
PlatformFrom $138,00125,000+Unlimited users, Unlimited servers, Unlimited streams, Unlimited signature domains, All event webhooks

For more details, please consult the official Postmark pricing page.

Pros

  • Straightforward setup
  • Separate sending streams
  • Fast email delivery
  • Transparent deliverability status
  • Inbound email support
  • Logs for up to 45 days
  • Real-time notifications with webhooks
  • Offers MCP agents 

Cons

  • You can reach Postmark customer support only via tickets and it’s not available 24/7.
  • To get dedicated IPs, you need to be sending at least 300,000 emails per month.

Developer experience

Jump to: Official API documentation

Postmark has official libraries for Ruby, RoR, .NET, Java, PHP, and Node.js.

The platform’s documentation is also very well organized, and it seems to be regularly updated. In translation: you don’t even need to be as experienced to use Postmark’s email API and start sending emails. 

Speaking of email sending, you get code snippets for every major programming language and web framework Postmark supports:

Security

The aspect I liked the most about Postmark’s security is the way it automatically blocks delivery for bounces and how detailed its activity logs are. It also has all important encryption protocols in place:

Encryption & transmission securityTLS 1.2+ enforced
Authentication & identity controlSPF, DKIM, DMARC
API & credentials securityRestricted API tokens, IP whitelisting.
Account access & user controlsMFA, team roles, activity feed
Abuse prevention & misuse protectionProactive spam filters, bounce management
Security event logging & notificationsDetailed activity logs, webhooks

Compliance

Besides allowing you to choose whether you want EU or US hosting, Postmark complies with key industry standards and certifications:

GDPR✅ Compliant
Data residency All data hosted in EU or US (choose)
SOC 2, ISO 27001, HIPAA✅ 
User rights supportData subject rights support
LoggingGranular activity logging
DPA✅ Available upon request

Testimonials

Generally, people like Postmark’s SMTP and API for sending transactional emails, although I’ve noticed that some have an issue with the platform’s customer support team not working around the clock and having only ticket support:

Source: G2

On the other hand, some people like the fact that Postmark supports whitelabel domains and has solid deliverability:

Source: Capterra

If you’re interested in exploring what Postmark users have to say about the platform and its API, you can also check out its customers page

Transactional email API comparison criteria

To select the best email API on the market, I used the following criteria:

Email infrastructure

When talking about email infrastructure, we are actually talking about the following aspects:

Deliverability

Email APIs with high deliverability rates are more likely to send your emails to your recipients’ inboxes, instead of delivering them to the spam folder. 

However, as the exact rates are not publicly available, we’ve run a few deliverability tests for some of the providers on the list. And yes, the tests were fair for all email API providers: we made sure to use a free plan, shared IP, the same template, and no domain warmup. 

Here are the results (other providers’ results are on the way):

Email service providerEmail placement result
MailtrapInbox: 78.8%
Tabs: 4.8%
Spam: 14.4%
Missing: 2.0%
Amazon SESInbox: 77.1%
Tabs: 1.9%
Spam: 20.0%
Missing: 1.0%
MailgunInbox: 71.4%
Tabs: 3.8%
Spam: 23.8%
Missing: 1.0%
SendGridInbox: 61.0%
Tabs: 1.0%
Spam: 17.1%
Missing: 20.9%
PostmarkInbox: 83.3%
Tabs: 1.0%
Spam: 14.3%
Missing: 0.9%

For the full results and insights into the methodology we used, check out our dedicated blog post on email deliverability comparison.

Reliability & uptime

As far as reliability goes, an ideal email API is one with the least amount of downtime and always-ready customer support. So, I’ve scoured the web looking for downtime reports and checked out each API’s customer support availability.

To take it one step further, I’ve checked out various status pages like this one or delivery pages like this one.

Scalability & throughput handling

As your business grows, the email API you use will have to adapt to your growing needs and handle different email-sending volumes without compromising the quality of the service.

And although not all services on this list provide good scalability, you can send large amounts of emails with all of them.

IP pools & email streams

A solid IP infrastructure consists of features such as dedicated IPs, manual or auto warm-up, IP pool management, etc. 

I’ll also look into separate sending streams, which go a long way when it comes to deliverability since they allow you to send transactional and marketing emails on separate IPs. 

Now, some API providers offer dedicated infrastructures through IP pooling or email queuing, but a true separate stream is what you need if you’re a high-volume email sender. That is, if you don’t want your emails to hit spam filters or damage your sender reputation.

Pricing comparison

An email API should be affordable, but at the same time, not cut back on important features like email logs or dedicated IP addresses. It should offer value for money and also let you choose a pricing plan according to the size of your business. For now, check out what you can expect from each provider’s pricing plans:

SMTP provider10,000 emails50,000 emails100,000 emails250,000 emails
Mailtrap$15$20$30$200
Mailgun$15$35$75$215
SendGrid$19.95$35$60$200
Amazon SES$1,00$5,00$10,00$25,00
Postmark$15$50$100$250

Ease of integration

Most providers nowadays support simple mail transfer protocol (SMTP), allowing you to send emails via relay mechanisms over RESTful API endpoints. To help you integrate the API with your project, they also offer SDKs, toolkits that contain everything from installation instructions to pre-built components and resources.

So, for research purposes of this article, I’ll dive head first into the documentation, GitHub repositories, and SDKs of every email service I review. I’ll check which programming languages they’re compatible with, the usage examples they offer, and more!

I’ll also look for quality-of-life features, which aren’t necessary at all, but can make your developer team’s lives easier. A great example is MCP servers, such as Mailtrap MCP and Postmark MCP. You can hook these up to your IDE or preferred AI helper, then send transactional emails or smoothen out your workflow.

Webhooks

With webhooks, you can get instant notifications when your emails get delivered or land in spam, when someone unsubscribes, etc. You can monitor your engagement, debug workflows, you name it.

Since all email API providers on this list offer webhooks, I’ll compare them by the types of events they support and their retry logic. 

Email analytics

Detailed analytics on email performance, such as open rates, bounce rates, and click-through rates, go a long way in improving your deliverability.

This is especially true since all major inbox providers nowadays have their own regulations, including:

To comply with these, you need to be able to track your emails. For instance, Google requires you to stay under 0.1% spam rate if you don’t want to get blocked.

However, it’s important to make a distinction in the analytics email API providers offer. Some provide dedicated solutions like Mailtrap, while others, like Amazon SES, require integration with other services such as CloudWatch.

Security & compliance

Security 

Every email API should place strong emphasis on encrypting data, requiring authentication, and similar security measures. 

For the purposes of this article, I’ve researched how each provider handles encryption, API keys, how granular their user access is, if they support TLS and STARTTLS protocols, etc.

P.S. Over at Mailtrap, we’ve recently conducted in-depth research on email security for the top providers in the industry. Check it out! 

Compliance

Not complying with regulations like GDPR (EU) or CCPA (US), CAN-SPAM Act, and others can lead to considerable fines. For instance, not complying with the CAN-SPAM Act, you can get fined up to $44k per email.

So, to see whether an email API provider helps you comply with all the regulations, I’ve dug through pages like this one or this one.

Since the Mailtrap team leaves no stone unturned, we’ve also compared the compliance of the top providers. You can read it here.

Onboarding, UX & support

HTML previews, blacklist checks, email logs, webhook responses in JSON format, and templates are only some of the features every email API should offer to cater to diverse use cases and enhance user experience.

Additionally, verifying your domain shouldn’t be a headache, and a blocker shouldn’t take forever to deal with. That’s why I’ve checked what sort of customer support the API providers from this list offer and whether:

  • Their team is available around the clock or not
  • You get help if you’re migrating from another provider
  • They provide email deliverability consultations

Customer experience

I’ll make sure to provide you with user testimonials for each platform I’ve found across the various social media platforms.

And I’ll also dig out the ratings from popular review websites such as G2 or Capterra.

Wrapping up

And we’ve made it!

I hope you enjoyed going through the haystack of email infrastructure services and best email APIs with me and that I’ve made your decision on which one to use a bit easier.

And as if you haven’t had enough of tables throughout this article, here’s another one that sums up the best email APIs for you:

Email APIBest forIntegrationPricing
MailtrapHigh-volume product companiesNode.js, PHP, Ruby, Python, Elixir, JavaFrom $15
MailgunDeveloper teamsPython, Go, Node.js, PHP, Java, RubyFrom $15
SendGridEnterprise usersC#, Go, Java, Node.js, PHP, Python, RubyFrom $19.95
Amazon SESAWS users and devsJava, .NET, PHP, Python, Ruby, Go$0.10 per 1,000 emails
PostmarkTransactional emailsRuby, RoR, .NET, Java, PHP, Node.jsFrom $15

Frequently asked questions

What is the best email API?

Since every team has its specific goals, needs, and wants, there really is no best email API. However, Mailtrap Email API is quite flexible and lets you control your sending process and fine-tune it according to your requirements. 

Which email API offers the best deliverability rates?

Based on the deliverability tests we’ve recently performed, Mailtrap and Postmark have the best deliverability rates. Using free plans, shared IPs, and identical email template, we’ve managed to achieve 78.8% deliverability rate with Mailtrap, whereas Postmark reached 83.3%.

How do I choose the best email API for my application?

When choosing the best email API for your application, first take into consideration your team’s requirements and goals. Then, take into account an API’s email infrastructure, ease of integration, webhooks, email analytics, security & compliance, and, of course, customer support and pricing.

If you need help choosing an email API, refer to our guide on choosing an email service provider.  

]]>
How to Send Emails with Email API: Practical Examples in Popular Languages and Frameworks https://mailtrap.io/blog/api-send-email/ Wed, 23 Jul 2025 15:50:30 +0000 https://mailtrap.io/?p=30877 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.

Ready to deliver your emails?
Try Mailtrap for Free

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.
    • Mailtrap also offers and maintains official SDKs for PHP, Python, Ruby, Node.js, and Elixir. I’ll show you how to use them in a jiffy.
  • 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.

HTML email

Sending HTML emails in PHP couldn’t be easier as all you need to do is add the ->html() method.

To save you some time, I’ve prepared a code you can use to send an HTML email to multiple recipients and attach files to it:

<?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;
use Symfony\Component\Mime\Part\DataPart;

require __DIR__ . '/vendor/autoload.php';

// Your API token from here https://mailtrap.io/api-tokens


$apiKey = “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'))
    ->priority(Email::PRIORITY_HIGH)
    ->cc('mailtrapqa@example.com')
    ->addCc('staging@example.com')
    ->bcc('mailtrapdev@example.com')
    ->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')
    ->html(
        '<html>
        <body>
        <p><br>Hey</br>
        Learn the best practices of building HTML emails and play with ready-to-go templates.</p>
        <p><a href="https://mailtrap.io/blog/build-html-email/">Mailtrap's Guide on How to Build HTML Email</a> is live on our blog</p>
        <img src="cid:logo">
        </body>
    </html>'
    )
    ->embed(fopen('https://mailtrap.io/wp-content/uploads/2021/04/mailtrap-new-logo.svg', 'r'), 'logo', 'image/svg+xml');

// Add an attachment
$email->attachFromPath('/path/to/your/file.pdf', 'Filename.pdf', 'application/pdf');

// 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";
}

Send emails in Laravel

To quickly integrate the Mailtrap email API into your Laravel application, you can use the official PHP SDK and docs for the Laravel framework bridge. The Mailtrap library is also fully compatible with Laravel 9.x and above. 

For more information, read our complete guide on sending emails in Laravel which covers different sending methods as well.

Nonetheless, here’s an example of sending plain-text emails in Laravel;

  • Install the Mailtrap PHP client and dependencies using composer:
composer require railsware/mailtrap-php symfony/http-client nyholm/psr7
  • Next, add Mailtrap transport into your config/mail.php file:
<?php

return [
    /*
    |--------------------------------------------------------------------------
    | Mailer Configurations
    |--------------------------------------------------------------------------
    */
    'mailers' => [
    
            // start mailtrap transport
            'mailtrap' => [
                'transport' => 'mailtrap'
            ],
            // end mailtrap transport
    
    ]
];
  • Now, to the Laravel .env file, add your Mailtrap credentials:
MAIL_MAILER="mailtrap"
MAILTRAP_HOST="send.api.mailtrap.io"
MAILTRAP_API_KEY="YOUR_API_KEY_HERE"
MAIL_FROM_ADDRESS="name@registered_domain.com"
  • To send the email, create a mailable class:
php artisan make:mail WelcomeMail
  • Open the newly created WelcomeMail.php file in app/Mail directory, and configure it as follows:
<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Attachment;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Address;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Mail\Mailables\Headers;
use Illuminate\Queue\SerializesModels;
use Mailtrap\EmailHeader\CategoryHeader;
use Mailtrap\EmailHeader\CustomVariableHeader;
use Symfony\Component\Mime\Email;
use Symfony\Component\Mime\Header\UnstructuredHeader;

class WelcomeMail extends Mailable
{
    use Queueable, SerializesModels;

    private string $name;

    /**
     * Create a new message instance.
     */
    public function __construct(string $name)
    {
        $this->name = $name;
    }

    /**
     * Get the message envelope.
     */
    public function envelope(): Envelope
    {
        return new Envelope(
            from: new Address('jeffrey@example.com', 'Jeffrey Way'),
            replyTo: [
                      new Address('taylor@example.com', 'Taylor Otwell'),
                  ],
            subject: 'Welcome Mail',
            using: [
                      function (Email $email) {
                          // Headers
                          $email->getHeaders()
                              ->addTextHeader('X-Message-Source', 'example.com')
                              ->add(new UnstructuredHeader('X-Mailer', 'Mailtrap PHP Client'))
                          ;

                          // 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'))
                          ;
                      },
                  ]
        );
    }

    /**
     * Get the message content definition.
     */
    public function content(): Content
    {
        return new Content(
            view: 'mail.welcome-email',
            with: ['name' => $this->name],
        );
    }

    /**
     * Get the attachments for the message.
     *
     * @return array<int, \Illuminate\Mail\Mailables\Attachment>
     */
    public function attachments(): array
    {
        return [
           Attachment::fromPath('https://mailtrap.io/wp-content/uploads/2021/04/mailtrap-new-logo.svg')
                ->as('logo.svg')
                ->withMime('image/svg+xml'),
        ];
    }

    /**
     * Get the message headers.
     */
    public function headers(): Headers
    {
        return new Headers(
            'custom-message-id@example.com',
            ['previous-message@example.com'],
            [
                'X-Custom-Header' => 'Custom Value',
            ],
        );
    }
}
  • Create a Blade view template for your email in resources/views/emails/welcome.blade.php:
<p>Hey {{$name}}!</p>
<br>
<p>Welcome to the party! You've just joined the coolest club in town.</p>
  • To the app/routes/console.phpfile, add the CLI router:
<?php

use App\Mail\WelcomeMail;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Mail;

/*
|--------------------------------------------------------------------------
| Console Routes
|--------------------------------------------------------------------------
|
*/

Artisan::command('send-welcome-mail', function () {
    Mail::to('testreceiver@gmail.com')->send(new WelcomeMail("Jon"));
    // Also, you can use specific mailer if your default mailer is not "mailtrap" but you want to use it for welcome mails
    // Mail::mailer('mailtrap')->to('testreceiver@gmail.com')->send(new WelcomeMail("Jon"));
})->purpose('Send welcome mail');
  • Lastly, to send your email, call the CLI command:
php artisan send-welcome-mail

HTML email

To send an HTML email via Laravel, all you have to do is add HTML code to the Blade file we previously created (e.g., welcome.blade.php).

For a basic HTML message, use the code below:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <style>
        p {
            font-size: 12px;
        }

        .signature {
            font-style: italic;
        }
    </style>
</head>
<body>
<div>
    <p>Hey {{ $name }},</p>
    <p>Can your Laravel app send emails yet? 😉 </p>
    <p class="signature">Mailtrap</p>
</div>
</body>
</html>

If you want to customize your HTML emails further, be sure to give our Laravel HTML article a read.

Send emails in Python

Below I’ll show a basic example of how to send an email in Python. However, if you’d like to understand how to handle more complex email-sending scenarios in Python, I recommend reading our dedicated article on this topic.

Similarly to other languages and frameworks, once the Mailtrap account is all set, I’ll use Mailtrap’s official Python SDK to streamline the process of sending emails via the API in Python. 

Here’s how it works:

  • Open your terminal and run the following command: 
pip install mailtrap
  • Send a plain-text email by running this script:
from mailtrap import Mail, Address, MailtrapClient

# Create a Mail object with basic details for a plain text email
mail = Mail(
    # Specify the sender's email address and optional name
    sender=Address(email="mailtrap@example.com", name="Mailtrap Test"),
    # Specify one or more recipients; here we use a list with a single recipient
    to=[Address(email="your@email.com", name="Your Name")],
    # Subject of the email
    subject="Simple Plain Text Email",
    # The plain text content of the email
    text="This is a plain text email sent using the Mailtrap SDK. Simple and straightforward.",
    # Optional: categorize this email for easier sorting or management in the Mailtrap service
    category="Test",
    # Optional: Additional headers can be specified, but are not required for plain text emails
    headers={"X-Example-Header": "HeaderValue"}
)

# Initialize the MailtrapClient with your API token
client = MailtrapClient(token="your-api-key")

# Send the email using the client's send method
client.send(mail)

print("Plain text email sent successfully.")

Don’t forget to insert your Mailtrap credentials (e.g., verified sending domain and API key).

HTML email

To send an HTML email, simply adjust the script above by specifying the html parameter in the Mail object with the HTML content. Like so:

from mailtrap import Mail, Address, MailtrapClient

# Create a Mail object for sending an HTML email
mail = Mail(
    sender=Address(email="mailtrap@example.com", name="Mailtrap Test"),
    to=[Address(email="recipient@email.com", name="Recipient Name")],
    subject="Your HTML Email Subject Here",
    text="This is a fallback text for email clients that don't render HTML",
    html="""
    <!DOCTYPE html>
    <html>
        <head>
            <title>Email Title</title>
        </head>
        <body>
            <h1>Hello, World!</h1>
            <p>This is an <strong>HTML email</strong> sent from the Mailtrap Python SDK.</p>
            <p>Here's a link: <a href="https://example.com">Visit Example.com</a></p>
        </body>
    </html>
    """,
    # You can categorize this email or add custom headers as needed
    category="HTML Email",
    headers={"X-Custom-Header": "Value"}
)

# Initialize the MailtrapClient with your API token
client = MailtrapClient(token="your-api-key")

# Send the email
client.send(mail)

print("HTML email sent successfully.")

Send emails in Node.js

In this chapter, I’ll show you how to add email-sending functionality to your Node.js application with Mailtrap’s official SDK that allows easy integration.

The examples I’ll show you will be basic, but, if you’re feeling dev-savvy, feel free to check out our detailed article on sending emails in Node.js.

Now, let’s start by installing Mailtrap Node.js package with either npm or yarn:

npm install mailtrap

# or, if you are using yarn:

yarn add mailtrap

Then, send a plain text email by running the following code:

import { MailtrapClient } from "mailtrap"

/**
 * For this example to work, you need to set up a sending domain,
 * and obtain a token that is authorized to send from the domain.
 */

const TOKEN = "<YOUR-TOKEN-HERE>";
const SENDER_EMAIL = "<SENDER ADDRESS@YOURDOMAIN.COM>";
const RECIPIENT_EMAIL = "<RECIPIENT@EMAIL.COM>";

const client = new MailtrapClient({ token: TOKEN });

const sender = { name: "Mailtrap Test", email: SENDER_EMAIL };

client
  .send({
    from: sender,
    to: [{ email: RECIPIENT_EMAIL }],
    subject: "Hello from Mailtrap!",
    text: "Welcome to Mailtrap Sending!",
  })
  .then(console.log)
  .catch(console.error);

As Mailtrap’s Node.js package uses ECMAScript (ES) modules, I suggest adding “type:” “module” in your package.json file.

HTML email

Use the following code snippet to send an HTML email:

import { MailtrapClient } from "mailtrap"

/**
 * For this example to work, you need to set up a sending domain,
 * and obtain a token that is authorized to send from the domain.
 * @see https://help.mailtrap.io/article/69-sending-domain-setup
 */

const TOKEN = "<YOUR-TOKEN-HERE>";
const SENDER_EMAIL = "<SENDER@YOURDOMAIN.COM>";
const RECIPIENT_EMAIL = "<RECIPIENT@EMAIL.COM>";

const client = new MailtrapClient({ token: TOKEN });

client
  .send({
    category: "test",
    custom_variables: {
      hello: "world",
      year: 2022,
      anticipated: true,
    },
    from: { name: "Mailtrap Test", email: SENDER_EMAIL },
    to: [{ email: RECIPIENT_EMAIL }],
    subject: "Hello from 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>
          <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>
  `,
  })
  .then(console.log)
  .catch(console.error);

How to choose an email API provider

So far in the article, we’ve used Mailtrap Email API to send emails. However, I know that not every email API can fit all teams out there.

To see how Mailtrap compares to other APIs and help you choose the best solution for your team, we researched the top email API providers, focusing on flexibility. That is, the provider’s ability to send your emails reliably while allowing you to fine-tune your sending process. 

So, we sent emails with each API, tried different sending configurations, set up webhooks, played around with templates, and more, all the while taking the following into consideration:

  • Infrastructure and scalability 
  • Sending logic and performance
  • Integration and extensibility
  • Templates and personalization
  • Customer support

As a sneak peek, here’s a brief flexibility comparison between Mailtrap and Mailgun:

FeatureMailtrapMailgun
Dedicated IPsAvailable from 100k emails/month with auto warm-up. Available from 50k emails/month as an add-on and included from 100k emails/month.
Separate streams✅ Bulk and transactional
Rate handling✅ No limits, customizable throttling✅ Yes, limit not specified
Webhooks✅ Full events + logs✅ Full events
SDKsNode.js, PHP, Ruby, Python, Elixir, JavaPython, Go, Node.js, PHP, Java, Ruby
Templates✅ Handlebars✅ Handlebars + versioning
Customer supportTicket, chat, priority supportTicket, chat, and phone

To learn more about our methodology and get more in-depth information on technical tidbits like IP infrastructure, throttling, retry logic, etc., read our full comparison. 👀

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:

]]>