How to Send Email Using API or SMTP

On September 30, 2019
10min read
Zakhar Yung Technical Content Writer @Mailtrap

Which email transfer method should you use for sending transactional or bulk emails? Primarily, there are two options. A platform-agnostic SMTP relay is the most common one. It is based on the Simple Mail Transfer Protocol and sometimes is the only choice that makes sense. Web APIs, however, are better than the SMTP method in many use cases and have increased in popularity. You may also want to give it a shot. Let’s find out.

What is the difference between Web API and SMTP Relay?

The SMTP is a set of rules used to send emails. SMTP relay refers to the process of transferring emails from one mail server to another. In practice, this term denotes the SMTP server that enables the relaying. For more on this, you can read our blog post about SMTP relay. Most email service providers (ESP) set up SMTP relay servers. This way, users can send their emails using the infrastructure of a sender with an outstanding reputation. 

API stands for an application programming interface. It lets you integrate different apps. A Web API or HTTP API is a type of interface where the communication takes place using the HyperText Transfer Protocol (HTTP). This is a universal web protocol for different kinds of data. If it’s used for email, a Web API is generally called an Email API. It allows a user app to access functions offered by ESPs for email handling.

What should I use: SMTP relay or Web API?

Your choice should depend on your needs and project requirements. Both email transfer methods focus on providing a high rate of email deliverability. But they differ in what approach they use. SMTP involves the back-and-forth communication (handshake) between the client and the server. Since these handshakes are many, the method is called chatty. SMTP relay is a good solution for casual email senders who need simplicity for basic tasks. You can use it to integrate with your CRM system or mail client. 

The Web API makes sending quicker because there is less back-and-forth required compared to the SMTP. Another benefit is additional functionality outside of pure email sending. For example, you can automate your transactions, track metrics, and so on. HTTP API is often the choice of marketers dealing with bulk emails and developers who build their own products. 

If you have no time for getting into the details of each email transfer method, check out the following brief takeaways. 

TL;DR comparison table: Web API or SMTP Relay

SMTP Relay

Web API

Protocol used

How it works

SMTP – Simple Mail Transfer Protocol

The client and the server communicate using multiple back-and-forths

HTTP – HyperText Transfer Protocol

Your app sends HTTP requests to use integrated functions of a third-party service

Pros

  • Easy to set up
  • Platform-independent
  • Simpler troubleshooting
  • Fast email delivery
  • No blockage
  • Optimized security
  • Analytics capabilities

Cons

  • Slow performance for bulk email
  • Changing deliverability of emails
  • Possible blockage of port 25
  • Complex solution that requires coding skills
  • Modifiability
  • Unlike SMTP, HTTP API does not have a unique specification, so each email service provider implements its own solution

Ease of testing

Yes

No

Mailtrap Email API applicability

Yes

Yes

It is the best option for

  • casual email senders
  • integration with a CRM system or mail client
  • marketers
  • bulk email senders
  • app developers

If the table has triggered interest, you’re welcome to read more. We will start with the most universal email transfer method.

SMTP relay explained

As you know, SMTP is a protocol with which your mail user agent (the client) sends emails to the server. Email sending is based on the conversation between the client and the server. It starts with the initiation of a TCP connection with a particular port. The client sends separate pieces of information, and the server needs to check the email and authentication. They talk to each other using SMTP commands and response codes. If everything is okay, the email is relayed to the receiving SMTP server. The sender’s and recipient’s SMTP servers have a similar conversation. The outcome is that the email will be either delivered, blocked, or put into the spam folder. The further delivery of the email to the recipient’s mail user agent is carried out via IMAP or POP3 protocol. Read more about email protocols in SMTP vs. IMAP vs. POP3.

Pros and cons of SMTP relay

Pros:

No hassle with setup

All you need to do is input your SMTP credentials to your mail user agent. After that, you can send emails right from your system. No coding skills are required to do that.

Platform-independent

The SMTP connection has no specific restrictions that the app or system must integrate.

Detailed conversation between the client and server

Each command sent by the client to the server gets a response code, which always includes context. If there is an error, you’ll get an idea of what exactly went wrong.

Cons:

Bad choice for bulk email 

SMTP relay requires multiple communications between the client and the server. This not only increases the error rate but also slows down the sending of bulk emails. Furthermore, you’ll have to deal with Mail Merge and MIME. 

Changing deliverability

Most SMTP relay services use shared IP addresses, which affect the sender’s reputation. This, in turn, is crucial for deliverability – that’s why its rate may change all the time. A white label email marketing software can be a solution, but it requires some DNS tweaks. 

Blocked SMTP ports

Some environments may block SMTP due to built-in or firewall restrictions. Mostly, this refers to the use of port 25, which is one of the most abused ports for spamming. All these issues can be solved but it will take much of your time and effort.

Example of sending an email via SMTP 

Now, let’s take a look at a regular SMTP session between the client and the server.

As Mailtrap’s email sending solution, Mailtrap Email API offers both an SMTP server and an email API, we will use it to send an email via SMTP alongside one of the most common tools for SMTP server testing, Telnet.

If you are unfamiliar with Mailtrap Email API, then don’t worry, we will cover it a bit later on. 

If, on the other hand, you want to learn more about Telnet and SMTP server testing, then be sure to check out our How to Test SMTP Server article.

Note: Do keep in mind that before doing any sending using Mailtrap Email API you will need to create an account as well as add and verify your domain. The latter process is described in detail in this video.

To initiate the process of sending an email via SMTP,  you can use the following command:

>telnet send.smtp.mailtrap.io 2525
Connected to send.smtp.mailtrap.io

<220 send.smtp.mailtrap.io ESMTP
>EHLO client
<250-send.smtp.mailtrap.io
250-PIPELINING
250-SIZE 10485760
250-STARTTLS
250-ENHANCEDSTATUSCODES
250 8BITMIME

>AUTH LOGIN
<334 VXNlcm5hbWU6
//username encoded in BASE64 OTRiNzg0YjU5NzBlZGY=
>dXNlcm5hbWU=
<334 UGFzc3dvcmQ6
//password encoded in BASE64  MDFhNWQ1MTUwMTFmNmU=
>cGFzc3dvcmQ=
<235 2.0.0 OK
>MAIL FROM:<jon@snow.com>
<250 2.1.0 Ok
>RCPT TO:<sansa@stark.com>
<250 2.1.0 Ok
>DATA
<354 Go ahead
>From: jon@snow.com
>Subject: Test email
>To: sansa@stark.com 
>This is a body text 
>.
<250 2.0.0 Ok: queued
>QUIT

If you check the inbox of the recipient used in the command, the email should be there.

Web API explained

A web API is a type of interface where the communication takes place using web-specific protocols, mostly HTTP. It allows you to integrate functions from a third-party service into your own app. So, the web API is a sort of a bridge to other tools or services. Requests to web APIs use standard HTTP methods. The full list of them is CONNECT, DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT, and TRACE. An Email API is a web API that lets your app access functions provided by an ESP. In simple English, you add a few lines of code (API) to your app’s backend, and the email sending is triggered directly from there. 

Initially, web APIs were called web services. They were designed to be used as part of a service-oriented architecture (SOA) and to communicate using the Simple Object Access Protocol (SOAP). Today, most web-based APIs use Representational State Transfer (REST) as an architectural style. So, are REST APIs and HTTP APIs the same? Definitely not.

What is RESTful API?

RESTful API is an HTTP API that adheres to the REST architectural constraints. HTTP is a way to transfer files, while the REST is a set of rules about how to use transfer protocols including HTTP and SMTP. 

In practice, most RESTful APIs use HTTP as a transport layer, and most HTTP APIs can be very close to becoming a true RESTful API.

What does Web SMTP API stand for?

Many ESPs offer a Web SMTP API for sending emails via SMTP. These APIs are meant to work with any RFC-compliant SMTP server. You can integrate the SMTP API with any internal or third-party system and send emails from it. So, your emails will be delivered via SMTP, but you’ll get advanced control over your email sending. For example, you can label your emails, set filters for incoming data, create dynamic emails, track metrics, and many more. SMTP API is sort of a blend of Web API and SMTP relay. 

Pros and cons of Web APIs for email sending

Pros:

Fast delivery 

Each API call requires one back-and-forth between servers. This speeds up the delivery of each email by a few seconds. In terms of bulk email, this transfer method is the best available. 

No or almost no blockage

The world-wide-web itself runs on HTTP, and most firewalls allow HTTP connections. 

Optimized security 

The API key is an extra security layer provided by most email APIs. It ensures another level of authentication by generating separate credentials. This protects your account from misuse by phishers and spammers.

Analytics capabilities 

To assess an email campaign, analytics are required. Email APIs allow you to track different metrics. These include the number of emails delivered, opened or rejected, how many CTA links have been clicked, and so on. Also, you get extra functionalities like automation that are not available with SMTP relay. 

Cons:

The most common cons of Web APIs in comparison to the SMTP method include the need for coding skills and modifiability of APIs. Can those be deemed as a drawback? It depends. Most ESPs provide detailed documentation on how to use APIs by sending authenticated HTTP requests. There are also client libraries that make things easier. You don’t have to be a coding guru for this. But, you might run into trouble understanding how to use extra functionalities provided by an email platform.

Unlike the SMTP relay, email APIs get frequent modifications and, hence, updates. This should not be a pain since all the changes are meant to improve functionality.

Another drawback we should mention is the diversity in implementation. With SMTP relay, email providers use the general protocol to send emails; it is the same for all of them. With HTTP API, there is no unique specification. This means that every email service provider offers its own solution for HTTP email API.

Example of sending an email via HTTP API

In most cases, if you’re planning to use the HTTP API for sending email, you need to generate an access token as your calls will be sent to it. 

That will look something like this:

https://www.example.com/v1/METHOD?access_token=YOUR_API_TOKEN

For Mailtrap Email API, more specifically, the transactional email API it provides, the access token can be found in the Mailtrap account under API->API Tokens.

Here is an example of how to send an email with this token from cURL:

curl --request POST \
  --url https://send.api.mailtrap.io/api/send \
  --header 'Api-Token: ' \
  --header 'Content-Type: application/json' \
  --data '{
  "to": [
    {
      "email": "john_doe@example.com",
      "name": "John Doe"
    }
  ],
  "cc": [
    {
      "email": "jane_doe@example.com",
      "name": "Jane Doe"
    }
  ],
  "bcc": [
    {
      "email": "james_doe@example.com",
      "name": "Jim Doe"
    }
  ],
  "from": {
    "email": "sales@example.com",
    "name": "Example Sales Team"
  },
  "subject": "Your Example Order Confirmation",
  "html": "<p>Congratulations on your order no. <strong>1234</strong>.</p>",
  "text": "Congratulations on your order no. 1234",
  "attachments": [
    {
      "content": "PCFET0NUWVBFIGh0bWw+CjxodG1sIGxhbmc9ImVuIj4KCiAgICA8aGVhZD4KICAgICAgICA8bWV0YSBjaGFyc2V0PSJVVEYtOCI+CiAgICAgICAgPG1ldGEgaHR0cC1lcXVpdj0iWC1VQS1Db21wYXRpYmxlIiBjb250ZW50PSJJRT1lZGdlIj4KICAgICAgICA8bWV0YSBuYW1lPSJ2aWV3cG9ydCIgY29udGVudD0id2lkdGg9ZGV2aWNlLXdpZHRoLCBpbml0aWFsLXNjYWxlPTEuMCI+CiAgICAgICAgPHRpdGxlPkRvY3VtZW50PC90aXRsZT4KICAgIDwvaGVhZD4KCiAgICA8Ym9keT4KCiAgICA8L2JvZHk+Cgo8L2h0bWw+Cg==",
      "filename": "index.html",
      "type": "text/html",
      "disposition": "attachment"
    }
  ],
  "category": "API Test",
  "custom_variables": {
    "user_id": "45982",
    "batch_id": "PSJ-12"
  },
  "headers": {
    "X-Message-Source": "dev.mydomain.com"
  }
}'

SMTP relay vs. Web API – difference in email testing

Earlier, we blogged about how you can test SMTP relay. In short, you need to connect to the SMTP server and try to send an email from it. Since there are many back-and-forths between the client and the server, troubleshooting is not that hard. You’ll always get a code response with details of a failure. For more about SMTP commands and replies, you can read our blog post.

Rest APIs are more complex structures and require a holistic approach to testing. Also there are a few challenges you should expect when checking the functionality of a web API:

  • coding skills are a must for testing
  • parameter selection and combination, as well as call sequencing, are major challenges
  • no GUI is available for testing the app which complicates how to give input values
  • you need to test the exception handling function 
  • and more

As for tools for testing Web APIs, check out cURL, Postman, and SOAtest as the most worthwhile solutions. 

Top 6 providers of both SMTP relay and Web API services

In the end, let’s review some famous Email Service Providers that allow you to use both SMTP relay and Web API.

Mailtrap Email API

As mentioned earlier in the article, Mailtrap Email API is an email sending solution of the Mailtrap Email Delivery platform that offers both an email API and an SMTP server. Primarily geared towards developers and QAs, Mailtrap Email API offers actionable analytics for gaining more control over email deliverability and catching as well as fixing sending issues early on. Dedicated IPs, auto IP warmup, suppression lists, and more features intended to help you reach recipient inboxes are also part of the package, and you can test them out with the forever-free plan.

Gmail

Google provides both SMTP and REST API for free and is one of the most popular ESPs. You can encounter the mention of smtp.gmail.com server in numerous code samples around the web. The REST API is also a sort of trendsetter and can be a good option for beginners. Read more on how to send emails with Gmail API in our blog post.

Mailgun

Mailgun is a purely transactional email service for developers. It provides powerful email APIs for you to send, receive and track emails. If you prefer a traditional way of email transfer, you can try Mailgun’s SMTP relay service. 

Mailjet

Mailjet is another solution that focuses on both marketers and developers. The latter can benefit from SMTP relay and Send API for their needs. Which one is worth your attention? It’s up to you. 

Sendgrid

Sendgrid puts its emphasis on the Web API, which you can use for sending and tracking emails. But primarily, this service is a cloud-based SMTP provider. Except for email APIs, Sendgrid offers an SMTP API. This allows you to extend SMTP capabilities by adding JSON instructions to emails for additional tracking of events.

Pepipost

We were going to add Pepipost to our blog post about free SMTP servers, but for some reason, we failed to do this. This ESP, however, is worth considering. Pepipost provides a robust SMTP relay service and email APIs to integrate with many development frameworks. Their Forever Free Plan, in particular, may trigger you to try out this email service.

To wrap up

There is no one-size-fits-all email transfer method that you should use. SMTP relay is quite reliable and sustainable but it won’t guarantee high speed delivery. Web API, on the other hand, provides expanded functionality, but it’s more complex to use. Weigh all the pros and cons, so that your final decision will be the right one. Good luck!

Article by Zakhar Yung Technical Content Writer @Mailtrap