How to Send Email Using API or SMTP
Tags: webdev, productivity
Published: 2022-10-24 07:43:22

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](https://mailtrap.io/blog/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

![SMTPvsAPI](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t8cta7g3nibir4lcp373.png)

_For a detailed comparison head to the article on Mailtrap Blog, where you can find out about the difference between [Mailgun API vs SMTP](https://mailtrap.io/blog/smtp-or-web-api/) and discover other ESP providers which allow using both methods._

## 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](https://mailtrap.io/blog/smtp-commands-and-responses/). 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](https://mailtrap.io/blog/imap-pop3-smtp/).

### 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](https://mailtrap.io/blog/email-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. For this, we’ll use the fake SMTP server by [Mailtrap](https://mailtrap.io/) and one of the most common tools for testing – Telnet. We’ve already blogged about how to use it in [How to Test SMTP Server](https://mailtrap.io/blog/how-to-test-smtp-server/). 

```
>telnet smtp.mailtrap.io 25
<220 mailtrap.io ESMTP ready
>EHLO client
<250-mailtrap.io
<250-SIZE 5242880
<250-PIPELINING
<250-ENHANCEDSTATUSCODES
<250-8BITMIME
<250-DSN
<250-AUTH PLAIN LOGIN CRAM-MD5
<250 STARTTLS
>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 your Demo inbox, you’ll find the email there. That’s a huge benefit of using a fake SMTP server. Your emails won’t go to real recipients. Therefore you can use fake email addresses just like we did in the example above. 

## 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](https://mailtrap.io/blog/dynamic-email-content/), 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. But shit happens, and no one is bulletproof against it.

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. Your calls will be sent to it. It looks something like this:

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

Here is an example of sending an email with this token from cURL:

```
$ curl -v -X POST -H "Authorization: $EXAMPLE_API_KEY" \
	--data '{
	"recipients": [
	{
		"address": {
		"email": "recipient@test.com"
		}
	}
	],
	"content": {
	"text": "This is a test email",
	"subject": "Testing API",
	"from": "my@domain.com"
	}
}' https://www.example.com/v1/METHOD?access_token=YOUR_API_TOKEN
**   Trying XX.XX.XXX.XXX...
** Connected to api.example.com (XX.XX.XXX.XXX) port 443 (#0)
** TLS 1.2 connection using TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
** Server certificate: *.example.com
** Server certificate: RapidSSL SHA256 CA - G3
** Server certificate: GeoTrust Global CA
> POST v1/METHOD?access_token=YOUR_API_TOKEN HTTP/1.1
> Host: api.example.com
> User-Agent: curl/7.66.0
> Accept: */*
> Authorization: YSBmYWtlIGFwaSBrZXksIG1hZGUgeW91IGxvb2sh
> Content-Length: 312
> Content-Type: application/x-www-form-urlencoded
>
** upload completely sent off: 312 out of 312 bytes
< HTTP/1.1 200 OK
< Cache-Control: no-cache, no-store
< Content-Type: application/json
< Date: Tue, 17 Sep 2019 13:23:45 GMT
< Server: msys-http
< Vary: Accept
< Content-Length: 109
< Connection: keep-alive
<
** Connection #0 to host api.example.com left intact
{ "results": { "total_rejected_recipients": 0, "total_accepted_recipients": 1, "id": "102364612952283792" } }
}
```

## SMTP relay vs. Web API – difference in email testing
Earlier, we blogged about [how you can test SMTP relay](https://mailtrap.io/blog/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](https://mailtrap.io/blog/smtp-commands-and-responses/), 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. 

_Note: Those who opt for Web APIs miss out on using Mailtrap for development. This is a toolset based on a fake SMTP server, which you can use for email sending tests. Mailtrap provides its own API that allows developers to run integrational and load email tests. For more about using Mailtrap and its features, read the [Getting Started Guide](https://help.mailtrap.io/article/12-getting-started-guide?_ga=2.24041849.279296008.1666594957-1477730163.1665994203&_gac=1.114495093.1665994203.CjwKCAjw-rOaBhA9EiwAUkLV4vB9O5wWnPWTsF8ZefSRIhs11tv7ymzLgpoQdKsTfhjVexxqyqAQ7RoCgfkQAvD_BwE)._

## Top 5 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.

### 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](https://mailtrap.io/blog/send-emails-with-gmail-api/) in our blog post.

### Mailgun
[Mailgun](https://www.mailgun.com/) is a purely [transactional email service](https://mailtrap.io/blog/transactional-email-services/) 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. It offers 10K email free every month.

### Mailjet
[Mailjet](https://www.mailjet.com/) 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](https://sendgrid.com/) puts their 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](https://pepipost.com/) to our blog post about [free SMTP servers](https://mailtrap.io/blog/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 especially 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!