Skip to content
send.io
All posts

What is SMTP and how does it work

SMTP is a store and forward protocol that moves email from your application to a recipient's mail server through command sequences. This guide walks you through the command structure, port decisions, and choosing between raw SMTP, a relay, or an API without trial and error.

On this page
TL;DR: SMTP (Simple Mail Transfer Protocol) is a store-and-forward protocol that moves email from your application to a recipient's mail server through a fixed command-response sequence. You interact with it by sending commands like EHLO, MAIL FROM, and DATA to a server on port 587 (with STARTTLS) or 465 (implicit TLS). Understanding this sequence lets you choose between a raw SMTP connection, a relay service, or a modern email API without guessing. SMTP only sends. It cannot receive email or retrieve messages, so if your application needs inbound routing you must use IMAP, POP3, or a platform that delivers inbound messages to your webhook.

You can send a transactional email in a few lines of Python, but the moment you need to debug a 550 error or receive a reply, the abstraction breaks, and you're reading raw SMTP response codes to understand what RCPT TO rejected and why.

SMTP is the email protocol that still expects your application to have a line-by-line conversation with the server. This article walks through that conversation, the ports and security decisions involved, and the architectural choice between raw SMTP, a relay service, and an API. By the end, you will know which integration path fits your stack and what you are trading off with each approach. You will also learn why SMTP cannot receive email, and what you need instead when your application has to process replies, verification codes, or inbound routing.

Defining SMTP for backend integrations

RFC 5321 defines SMTP (Simple Mail Transfer Protocol) as the standard mechanism for transmitting email across networks. Developers asking "what is SMTP" usually need to understand why their application cannot receive email, or why a specific port configuration is failing. The protocol operates as a push mechanism: it moves messages from a sending client to a receiving server, but it does not retrieve messages for end users.

Modern mail servers implement ESMTP (Extended SMTP), which extends the base protocol with capabilities like authentication (AUTH) and transport layer security (STARTTLS) through extension commands the client and server negotiate during the initial handshake. The base protocol remains text-based and human-readable, which means you can literally telnet into a mail server and send an email by typing commands manually.

Standard SMTP command syntax

Every SMTP transaction follows a rigid grammar. The client issues a command, and the server responds with a three-digit status code plus a human-readable message. The sequence for a basic transaction looks like this:

S: 220 mail.example.com ESMTP Postfix
C: EHLO client.example.org
S: 250-mail.example.com
S: 250-PIPELINING
S: 250-SIZE 10240000
S: 250-VRFY
S: 250-ETRN
S: 250-STARTTLS
S: 250-AUTH PLAIN LOGIN
S: 250 8BITMIME
C: MAIL FROM:<sender@example.org>
S: 250 OK
C: RCPT TO:<recipient@example.com>
S: 250 OK
C: DATA
S: 354 End data with <CR><LF>.<CR><LF>
C: From: "Sender" <sender@example.org>
C: To: "Recipient" <recipient@example.com>
C: Subject: Test message
C:
C: This is the message body.
C: .
S: 250 OK: queued as 12345
C: QUIT
S: 221 Bye

The envelope commands (MAIL FROM and RCPT TO) control routing, while the DATA phase transmits the actual message content defined in RFC 5322. The server advertises its capabilities in response to EHLO, telling the client which extensions (like STARTTLS or AUTH) it supports before the transaction proceeds.

SMTP message transmission workflow

SMTP uses a store-and-forward architecture. When your application sends an email, it does not connect directly to the recipient's inbox. Instead, it submits the message to an outgoing SMTP server (often called a smart host or relay), which then takes responsibility for delivery.

The sending server queues the message and performs a DNS lookup to find the recipient's mail exchanger (MX record). It opens a new SMTP connection to that destination server and repeats the command sequence. When the destination server refuses the connection, the sending server retries with exponential backoff, typically over several days (RFC 5321 section 4.5.4.1 recommends at least 4–5 days), before it generates a bounce message.

This indirection is why SMTP is resilient but also why debugging is complex: your application hands off responsibility to a chain of intermediate servers, each of which may accept, reject, or defer the message independently.

Sending vs receiving: SMTP vs IMAP/POP3

A common point of confusion for developers new to email infrastructure: SMTP cannot receive email. SMTP moves messages from one server to another but does not retrieve them for end users. Mail clients use IMAP (RFC 3501) or POP3 (RFC 1939) to pull messages from a server. SMTP pushes. IMAP and POP3 pull. If your application needs to process incoming email (to handle replies or verification codes, for example), you need either an IMAP client polling a mailbox, or an inbound routing service that accepts SMTP transmissions and forwards the content to your application via webhooks.

Outbound only: Your app --SMTP--> Sending server --SMTP--> Recipient's mail server
Inbound only: Mail client <--IMAP / POP3-- Mailbox stored on the mail server

Anatomy of an SMTP delivery path

Tracing the message from your code to the recipient's mailbox shows where each relay hop sits. The diagram below traces the full path from your application code through each relay hop to the recipient's inbox.

Application --> SMTP client library --> Sending server --> DNS MX lookup --> Recipient MX server --> Mailbox

The journey involves distinct phases: connection establishment, authentication, envelope declaration, content transmission, and final routing via DNS.

Step 1: establishing the SMTP connection

Your application opens a TCP connection to an SMTP server on port 587 or 465 for submission (client to server), or on port 25 for server-to-server relay. The server sends a 220 greeting code immediately, signaling it is ready to receive commands.

Step 2: SMTP identity verification

The client sends EHLO (Extended Hello) with its hostname. The server responds with 250 and lists its capabilities. If the connection requires encryption, the client issues STARTTLS to upgrade the connection to TLS before proceeding. After the TLS handshake completes, the client sends EHLO again to re-negotiate capabilities, then sends AUTH to present credentials (usually a username and password, or an API key acting as a password).

Step 3: sending email message payloads

Once authenticated, the client declares the envelope sender with MAIL FROM:<address>, and the server validates the syntax and authorization before responding with 250 OK. The client then issues one or more RCPT TO:<address> commands to specify recipients, and each recipient generates a separate response from the server. Finally, the client issues DATA and waits for the 354 intermediate response before transmitting the headers and body of the message, terminating the content with a single period on a line by itself.

Step 4: routing to the mail exchanger

The sending server accepts the message and performs a DNS MX lookup for the recipient's domain. RFC 5321 section 5.1 requires the sender to check for MX records first. When any exist, the sender must reach the destination only through the hosts those records name, and it must not use address records for the domain directly. If MX records exist but none are usable, the sender must report an error instead of falling back to the A record. When no MX record exists, the sender treats the domain as having an implicit MX with a preference of 0 and uses the domain's A or AAAA record. The sending server then opens a new SMTP connection to the target mail exchanger on port 25 and repeats the entire command sequence to transfer the message.

Step 5: validating final SMTP status

After the final period of the DATA phase, the receiving server responds with a final status code. A 250 OK indicates the server has accepted responsibility for delivery. A 4xx code indicates a temporary failure (try again later), while a 5xx code indicates a permanent failure (do not retry without changes). Your application must interpret these codes correctly to avoid unnecessary retries or silent message loss.

Key SMTP commands and error code reference

Debugging SMTP requires fluency in the command vocabulary and the status code taxonomy. The commands are simple, but the response codes determine your error handling logic.

Core SMTP transaction commands

Command

Arguments

Purpose

HELO / EHLO

Client hostname

Identify the client. EHLO requests extension list

MAIL FROM

Reverse-path

Declare the envelope sender

RCPT TO

Forward-path

Declare a recipient (multiple allowed)

DATA

None

Signal start of message content

RSET

None

Abort the current transaction

VRFY

User name

Verify address existence (often disabled)

NOOP

None

No operation (keep-alive)

QUIT

None

Terminate the session

STARTTLS

None

Upgrade connection to TLS

AUTH

Mechanism

Authenticate the client

Standard SMTP status code ranges

SMTP status codes are three-digit numbers where the first digit indicates the category of response. These ranges determine your retry logic: a 4xx means retry, a 5xx means stop.

Code Range

Category

Meaning

Example Codes

2xx

Success

Command accepted

250 OK, 221 Closing

3xx

Intermediate

Waiting for more input

354 Start mail input

4xx

Transient Failure

Temporary issue. Retry later

421 Service unavailable, 451 Local error, 452 Insufficient storage

5xx

Permanent Failure

Fatal error, do not retry

550 Mailbox unavailable, 552 Storage exceeded, 554 Transaction failed

For granular error handling, RFC 3463 defines enhanced status codes in the format X.Y.Z (for example, 5.1.1 for bad destination mailbox address, or 4.2.2 for mailbox full) that appear after the basic three-digit code in modern server responses.

Implementing reliable SMTP retry loops

When you receive a 4xx response, you should implement an idempotent retry with exponential backoff. For example, retry after 5 minutes, then 10 minutes, then 20 minutes, then 40 minutes with jitter. If you receive a 5xx response, log the failure and alert your team. Retrying a permanent failure wastes resources and may damage your sender reputation.

A reliable implementation queues failed messages in a dead-letter queue after exhausting retry attempts, allowing for manual inspection or reprocessing. Never retry 5xx codes automatically, as they indicate issues like invalid recipients or policy rejections that will not resolve with time.

Standard SMTP ports and TLS security requirements

Port selection is a security decision, not a preference. The three standard SMTP ports serve distinct purposes and carry different encryption expectations.

Port 25 for unencrypted SMTP relay

Port 25 serves server-to-server communication (relay). The port historically operated without encryption, though modern servers attempt STARTTLS negotiation when both sides support it. Most residential ISPs and cloud providers block outbound port 25 by default to prevent spam, so it is not a practical choice for client submission from applications hosted on AWS, GCP, or Azure.

Configuring STARTTLS on port 587

RFC 6409 defines port 587 as the modern standard for message submission. It requires authentication and mandates the use of STARTTLS to encrypt the connection before you transmit credentials. Use this port when configuring an application to send through an SMTP relay service.

Port 465: SMTP over SSL

IANA originally assigned port 465 for SMTPS (SMTP over SSL), deprecated it, and then RFC 8314 reinstated it for implicit TLS submission. Unlike port 587, which starts unencrypted and upgrades via STARTTLS, port 465 assumes TLS from the first packet. Both ports provide equivalent security when you configure them correctly.

How to determine your SMTP port

Port

Encryption

Primary Use Case

Cloud Provider Blocking

25

Optional STARTTLS

Server-to-server relay

Blocked by AWS, GCP, Azure

587

STARTTLS required

Client submission with auth

Open

465

Implicit TLS

Client submission (legacy, reinstated)

Open

Use port 587 with STARTTLS for most client submission scenarios. Use port 465 if your client library does not support STARTTLS negotiation but does support implicit TLS. Avoid port 25 for application sending. When configuring your SMTP settings, verify whether your provider expects STARTTLS or implicit TLS, as sending the wrong handshake type will cause connection failures.

Infrastructure options for reliable email delivery

You have three architectural choices for sending email from an application: direct SMTP socket communication, an SMTP relay service, or a modern email API. Each carries different operational overhead.

How SMTP servers process email

An SMTP server (Mail Transfer Agent) accepts messages, queues them for delivery, and handles retries. Running your own SMTP server requires managing IP reputation, handling bounces, maintaining suppression lists, and configuring DNS records (SPF, DKIM, DMARC) to prove you are authorized to send for your domain.

When to use an SMTP relay service

An SMTP relay service accepts messages from your application via SMTP and handles the delivery infrastructure for you. You authenticate to the relay, which then routes messages to the appropriate MX servers. This removes the burden of IP warming, blacklist monitoring, and bounce processing, but still requires you to manage the SMTP conversation in your code.

Some relay services also handle inbound traffic. send.io's inbound routing delivers the full message body, headers, and Base64-encoded attachments to your webhook endpoint in one call. Resend's inbound webhook, by contrast, delivers email metadata only, so your application has to make a follow-up API request to fetch the message body and attachments. If your application needs to receive verification codes, process replies, or route inbound messages to AI agents, confirm the relay you're evaluating treats inbound routing as a first-class feature rather than a metadata-only afterthought. The send.io documentation describes how its inbound routing and webhook payloads work.

SMTP delivery and the MX lookup path

When using a relay or direct SMTP, the final hop depends on the MX lookup. The sending server queries DNS for the recipient's domain, sorts the returned MX records by priority, and attempts delivery to each in turn. If the primary MX host is unreachable, it tries the backup. This DNS dependency means that email delivery is only as reliable as your DNS infrastructure and the accuracy of your MX records.

Choosing between direct SMTP and API integrations

The decision between raw SMTP and an email API affects your error handling, observability, and maintenance burden.

Direct SMTP implementation use cases

Direct SMTP (using libraries like Python's smtplib or Node.js nodemailer) makes sense when you need to send email through an existing internal relay, or when you require minimal external dependencies. It is also the only option when integrating with legacy systems that only speak SMTP. However, you must implement your own queuing, retry logic, and bounce handling, and you gain little visibility into delivery status beyond the initial 250 OK from your immediate relay.

Scaling delivery with email APIs

Modern email APIs replace the SMTP conversation with HTTP requests. Instead of managing socket connections and parsing 250 vs 550 responses, you POST JSON to an endpoint and receive a structured response with a message ID. APIs typically handle retries, provide delivery webhooks, and abstract away the command sequence. The send.io API reference documents the request and response formats for its Transactional Email API.

Direct SMTP vs API call comparison

Python's smtplib requires managing the socket connection, TLS upgrade, and command sequence. The hostname smtp.example.com is a placeholder: your SMTP hostname comes from your provider's SMTP settings, and for send.io it is listed in the SMTP relay documentation.

import smtplib
from email.mime.text import MIMEText

msg = MIMEText("This is the message body.")
msg['Subject'] = "Test message"
msg['From'] = "sender@example.org"
msg['To'] = "recipient@example.com"

with smtplib.SMTP("smtp.example.com", 587) as server:
server.starttls()
server.login("username", "password")
server.send_message(msg)

An email API reduces this to a single HTTP POST with structured error handling:

import requests

response = requests.post(
"https://api.sendio.run/emails",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={
"from": "sender@example.org",
"to": "recipient@example.com",
"subject": "Test message",
"text": "This is the message body."
}
)
print(response.json())

You no longer manage TLS negotiation, connection pooling, or retry state. The API returns a message ID you can reference in delivery webhooks, and the platform handles queue management and bounce processing for you.

Operational overhead of SMTP vs APIs

Approach

Pros

Cons

When to use

Direct SMTP socket

No vendor lock-in, works with any compliant server, minimal external dependencies

Must implement queuing, retry logic, bounce handling, and error parsing. Limited delivery visibility

Legacy system integration, existing internal relay, minimal dependency requirements

SMTP relay service

Handles IP reputation, DNS authentication, bounce processing, and retry infrastructure

Still requires managing SMTP conversation in code, connection pooling, and TLS validation

Need production deliverability without API dependency, compatible with existing SMTP client libraries

Email API

Structured HTTP requests replace socket management, built-in webhooks for delivery events, provider handles retries

Vendor-specific contract, potential lock-in without compatibility layer

Modern applications prioritizing observability and reduced operational overhead

SMTP requires you to manage connection pooling, TLS certificate validation, and credential rotation. APIs reduce this to an HTTP client and an API key. However, SMTP works with any compliant server as a standardized protocol, whereas an API ties you to a specific vendor's contract.

If you choose an API, verify that the provider offers webhooks for delivery events (delivered, bounced, complained) so you can update your database state asynchronously. If you choose SMTP, implement a dead-letter queue for failed messages and configure your retry logic to follow the 4xx vs 5xx distinction.

If your application needs to receive email in addition to sending it, or if you want to provision isolated inboxes for AI agents with scoped credentials, you cannot solve that with SMTP alone. Evaluate platforms that handle both directions under one API, and test the inbound routing behavior in the sandbox before committing to an integration. If your current setup splits inbound and outbound across two providers, send.io handles both under one API, and the documentation covers inbound routing and agent inboxes.

FAQs

What is SMTP service used for?

An SMTP service accepts outgoing email from your application and routes it to the recipient's mail server, handling queuing, retries, and DNS MX lookups.

Do you need an SMTP server to send email?

Yes, your application must hand the message to an SMTP server, whether you run your own, use a cloud provider's relay, or use an email API that abstracts the SMTP layer away from your code.

How do you find your SMTP settings?

Look for the outgoing mail server configuration in your provider's documentation. You need the hostname, port (usually 587 or 465), encryption method (STARTTLS or SSL/TLS), and authentication credentials. If you use send.io, start with the send.io documentation.

Can SMTP receive email or only send it?

SMTP only sends. To receive email, you need IMAP, POP3, or an inbound routing service that accepts SMTP transmissions and forwards the content to your application via webhooks.

What happens if SMTP authentication fails?

The server responds with a 535 authentication failed error during the AUTH phase. Check that your username and password (or API key) are correct, and ensure you are connecting to the correct port with the required encryption method.

Key terms glossary

SMTP (Simple Mail Transfer Protocol): The standard protocol for sending email across networks, defined in RFC 5321. It operates as a store-and-forward system using a command-response sequence.

ESMTP (Extended SMTP): An extension of SMTP that allows servers to advertise additional capabilities like authentication and encryption through the EHLO command.

MX Record (Mail Exchanger Record): A DNS record that specifies which mail servers accept email for a domain. SMTP servers query MX records to determine where to route outgoing messages.

STARTTLS: A command that upgrades a plain-text SMTP connection to an encrypted TLS connection, typically used on port 587.

DKIM (DomainKeys Identified Mail): An email authentication method that cryptographically signs messages to verify they were not altered in transit, defined in RFC 6376.

SPF (Sender Policy Framework): A DNS record that specifies which IP addresses are authorized to send email on behalf of a domain, defined in RFC 7208.

DMARC (Domain-based Message Authentication, Reporting and Conformance): A policy framework that tells receiving servers how to handle messages that fail SPF or DKIM checks, defined in RFC 7489.

SMTP Relay: A third-party server that accepts email from your application and forwards it to the destination, handling queuing and retries on your behalf.

IMAP (Internet Message Access Protocol): A protocol for retrieving and managing email stored on a server, distinct from SMTP which only sends.

POP3 (Post Office Protocol version 3): An older protocol for downloading email from a server to a local client, typically deleting the server copy after retrieval.