Receiving email with Nodemailer
Nodemailer cannot receive email. This is not a configuration problem — it is what the library is. What you actually need is an SMTP server to accept the mail, or a provider that accepts it for you and hands you the message. This guide covers the three approaches people try, why two of them stall, and the one that runs in production.
The short answer
Nodemailer is a transport: it speaks SMTP to a server that accepts
mail for delivery. Receiving is the opposite direction — something has to hold
port 25, terminate TLS, run SPF/DKIM/DMARC checks, and decide what to do with
the message. Nodemailer has none of that, and its API has no
receive().
npm install nodemailer
# Nodemailer's own docs, on what it is:
# "Send e-mails from Node.js – easy as cake!"
# There is no receive() in the API. There is no IMAP client. What people try instead
1. Point Nodemailer at a server and hope
Configuring host/port tells Nodemailer where to
send. It never opens a listening socket, so no mail arrives. If a
tutorial shows its own server accepting the message, that server is a separate
SMTP process — Nodemailer is still only sending to it.
2. Poll an IMAP mailbox
If you already own a mailbox, an IMAP client can read it. This works, and it is how mail-to-app integrations were built for years — but it is pull-based, it needs a stored password per mailbox, and it scales by polling more often.
import { ImapFlow } from "imapflow";
// The only way to *receive* with an IMAP library: poll a mailbox you already own.
const client = new ImapFlow({
host: "imap.example.com",
port: 993,
secure: true,
auth: { user: "support@example.com", pass: process.env.IMAP_PASSWORD },
});
await client.connect();
const lock = await client.getMailboxLock("INBOX");
try {
// IMAP is a pull protocol: you learn about mail when you ask.
for await (const message of client.fetch("1:*", { envelope: true, source: true })) {
console.log(message.envelope.subject);
}
} finally {
lock.release();
await client.logout();
} For a shared support address this is fine. For anything user-generated — a fresh address per user, per project, per tenant — you end up provisioning mailboxes and polling all of them.
3. Run your own SMTP server
This is the honest self-hosted answer: something like Haraka or Postal on a box with a public IP, port 25 open, a PTR record that matches, valid TLS, and spam handling. It works, it is a weekend of setup, and then it is yours to operate forever. If that is what you want, see the self-hosted path.
What actually works: accept the mail somewhere that gives you JSON
An inbound email API terminates SMTP for you and POSTs the parsed message to your endpoint — the same shape as a webhook from Stripe. No mailbox to poll, no server to operate, no IMAP credentials.
import express from "express";
import { MailKite } from "mailkite";
const SECRET = process.env.MAILKITE_WEBHOOK_SECRET;
const app = express();
// Raw body — the signature is over the exact bytes.
app.use("/hooks/email", express.raw({ type: "application/json" }));
app.post("/hooks/email", (req, res) => {
if (!MailKite.verifyWebhook(req.headers["x-mailkite-signature"], req.body, SECRET)) {
return res.sendStatus(401);
}
const event = JSON.parse(req.body.toString("utf8"));
if (event.type === "email.received") {
// Already parsed: subject, from, text, html, attachments, auth verdict.
const { subject, from, text } = event.data;
console.log(from, subject, text?.slice(0, 80));
}
res.sendStatus(200); // ack fast; do the work async
});
app.listen(3000);import os
from flask import Flask, request, abort
from mailkite import verify_webhook, reply_ok
SECRET = os.environ["MAILKITE_WEBHOOK_SECRET"]
app = Flask(__name__)
@app.post("/hooks/mailkite")
def hook():
sig = request.headers.get("x-mailkite-signature", "")
if not verify_webhook(sig, request.get_data(), SECRET):
abort(401)
event = request.get_json()
# ...handle event["type"] == "email.received"
# Confirm receipt: returns the JSON body {"status":"ok"}.
return reply_ok(), 200, {"content-type": "application/json"}<?php
$mk = new \MailKite\Client(""); // no API key needed to verify
$secret = getenv("MAILKITE_WEBHOOK_SECRET");
$signature = $_SERVER["HTTP_X_MAILKITE_SIGNATURE"] ?? "";
$rawBody = file_get_contents("php://input");
if (!$mk->verifyWebhook($signature, $rawBody, $secret)) {
http_response_code(401);
exit;
}
$event = json_decode($rawBody, true);
// ...handle $event["type"] === "email.received"
header("content-type: application/json");
echo $mk->replyOk(); // {"status":"ok"}// Spring Boot
@PostMapping(value = "/hooks/mailkite", produces = "application/json")
public ResponseEntity<String> mailkite(
@RequestHeader("x-mailkite-signature") String signature,
@RequestBody byte[] rawBody) throws Exception {
MailKite mk = new MailKite(""); // no API key needed to verify
String body = new String(rawBody, StandardCharsets.UTF_8);
if (!mk.verifyWebhook(signature, body, System.getenv("MAILKITE_WEBHOOK_SECRET"))) {
return ResponseEntity.status(401).build();
}
// ...handle the event
return ResponseEntity.ok(mk.replyOk()); // {"status":"ok"}
}http.HandleFunc("/hooks/mailkite", func(w http.ResponseWriter, r *http.Request) {
rawBody, _ := io.ReadAll(r.Body)
sig := r.Header.Get("x-mailkite-signature")
if !mailkite.VerifyWebhook(sig, string(rawBody), secret) {
w.WriteHeader(http.StatusUnauthorized)
return
}
var event map[string]any
json.Unmarshal(rawBody, &event)
// ...handle event["type"] == "email.received"
w.Header().Set("content-type", "application/json")
w.Write([]byte(mailkite.ReplyOk())) // {"status":"ok"}
})require "sinatra"
require "json"
require "mailkite"
post "/hooks/mailkite" do
raw_body = request.body.read
sig = request.env["HTTP_X_MAILKITE_SIGNATURE"]
halt 401 unless Mailkite.verify_webhook(sig, raw_body, ENV["MAILKITE_WEBHOOK_SECRET"])
event = JSON.parse(raw_body)
# ...handle event["type"] == "email.received"
content_type :json
Mailkite.reply_ok # {"status":"ok"}
end The payload is already parsed and already carries the auth verdict, so you do not run a MIME parser or re-check SPF yourself:
{
"id": "msg_4f3c1a9e2b7d48e1a05c6f8b3d2e7a91",
"type": "email.received",
"from": { "address": "ada@example.com", "name": "Ada Lovelace" },
"to": [{ "address": "support@myapp.ai", "name": "Support" }],
"subject": "Re: invoice #1042",
"text": "Looks good — approved!",
"html": "<p>Looks good — approved!</p>",
"textFromHtml": null,
"threadId": "<a1b2c3@mail.example.com>",
"receivedAt": 1785196800000,
"receivedAtIso": "2026-07-28T00:00:00.000Z",
"auth": {
"spf": "pass", "dkim": "pass", "dmarc": "pass",
"spam": "ham", "spamScore": 0.05, "spamSignals": []
},
"attachments": [
{
"id": "msg_4f3c1a9e2b7d48e1a05c6f8b3d2e7a91:0",
"filename": "po.pdf",
"contentType": "application/pdf",
"size": 18213,
"contentId": null,
"disposition": "attachment",
"url": "https://api.mailkite.dev/att/4f3c1a9e2b7d48e1a05c6f8b3d2e7a91/0?exp=…&sig=…",
"content": null
}
]
}
Verify the signature before you parse anything, and acknowledge fast — queue the
work and return 200. Slow handlers cause retries, and retries mean
duplicate tickets.
Keep Nodemailer for sending
Nothing here asks you to drop Nodemailer. Receiving and sending are separate concerns; keep the transport you have, and if you would rather send through the same verified domain you receive on, point it at the SMTP relay:
import nodemailer from "nodemailer";
// If you already send with Nodemailer, keep it. Point the transport at MailKite
// and the same code sends over your verified domain.
const transport = nodemailer.createTransport({
host: "smtp.mailkite.dev",
port: 587,
secure: false,
auth: { user: "mailkite", pass: process.env.MAILKITE_API_KEY },
});
await transport.sendMail({
from: "support@yourdomain.com",
to: "ada@example.com",
subject: "Re: Can't update my card",
text: "Sorted — try again now.",
}); Summary
- Nodemailer sends. It cannot listen for mail, and no option makes it.
- IMAP polling works for a mailbox you own — poorly for one address per user.
- Self-hosting an MX is real work: port 25, PTR, TLS, spam, uptime.
- An inbound webhook gives you parsed JSON and a signature, and needs one MX record.
Ready to try it? Add a domain and receive your first email — a free subdomain needs no DNS at all.