Send transactional emails with Nodemailer

Contents

If your app sends email with Nodemailer, you can send that email through PostHog. Change the transport, and keep every sendMail call. Each message becomes one email sent from your code, so PostHog shows its sends, metrics, and engagement events.

Before you start, create a project secret API key with the Transactional email scope, and configure a channel with a verified sender.

Install

Terminal
npm install posthog-node@5 nodemailer@10

Create the transport

Pass a PostHog client with your secret key to createPostHogTransport, and give the result to Nodemailer:

JavaScript
import nodemailer from "nodemailer"
import { PostHog } from "posthog-node"
import { createPostHogTransport } from "posthog-node/nodemailer"
const posthog = new PostHog("<ph_project_token>", {
host: "https://us.i.posthog.com",
secretKey: process.env.POSTHOG_PROJECT_SECRET_API_KEY,
// This client only sends email, so it doesn't poll flag definitions with the secret key
enableLocalEvaluation: false,
})
export const transporter = nodemailer.createTransport(
createPostHogTransport({ client: posthog, defaultTemplateKey: "app-email" })
)
  • client – A posthog-node client with secretKey set to your project secret API key. See set up the client for the key's scope and local evaluation.
  • defaultTemplateKey – The template key of a message that doesn't set one. It defaults to nodemailer.

On PostHog Cloud, the client sends email to your region's app host. If you send through a reverse proxy or a self-hosted PostHog, set appHost on the client. See use a proxy or self-hosted PostHog.

Send an email

Your sendMail calls stay the same:

JavaScript
const info = await transporter.sendMail({
from: "Hedgebox <orders@example.com>",
to: "jane@example.com",
subject: "Your order shipped",
html: "<p>Your order is on its way.</p>",
text: "Your order is on its way.",
})

info.messageId is PostHog's message ID. Use it with posthog.emails.get to check the email's status.

  • Sender – from needs an address on a domain that your project verified. Without from, PostHog uses the project's default sender.
  • Recipients – A message has exactly one to address. cc, bcc, and replyTo take a list. PostHog keeps the display name of from, and sends the other addresses without their names.
  • Attachments – Nodemailer reads each file of attachments, and posthog-node uploads it to PostHog before it sends the email. An inline image needs a cid.
Attachments are temporarily unavailable

A message with attachments fails, and PostHog sends nothing. Leave out attachments to send the email. cc and bcc still work. See copies and attachments.

Set PostHog options

Put PostHog's options for one message in posthog:

JavaScript
await transporter.sendMail({
from: "Hedgebox <security@example.com>",
to: user.email,
subject: "Reset your password",
html: `<p><a href="${resetLink}">Reset your password</a></p>`,
posthog: {
template_key: "password-reset",
distinct_id: user.id,
idempotency_key: `password-reset-${resetRequest.id}`,
sensitive: true,
},
})
  • template_key – Names the email, such as password-reset. PostHog groups the email's metrics and sends under this key. Without it, the transport uses defaultTemplateKey. Use letters, digits, hyphens, and underscores, up to 400 characters.
  • distinct_id – Records the email on the person with this distinct ID. Without it, PostHog uses a person whose distinct ID is the to address. See link emails to your users.
  • idempotency_key – Identifies this one email. PostHog sends an email only once for each key, for 24 hours after it queues the email. See send mail from a queue.
  • sensitive – Marks the email as sensitive, for login links, reset tokens, or codes. PostHog keeps its links as they are unless tracking turns clicks on, and keeps its subject and content out of events and logs. If you leave it out, the email takes the setting of the template with the same key, or is sensitive when no template has that key. See sensitive emails.
  • tracking – What PostHog tracks for the email: true or false for everything, or an object such as { opens, clicks, engagement }. If you leave it out, PostHog tracks opens and captures engagement events, and tracks clicks only when the email isn't sensitive. See open and click tracking.

In TypeScript, importing posthog-node/nodemailer adds posthog to Nodemailer's message type.

Send mail from a queue

The client retries some failed requests for you, such as network errors and a 503, with the same idempotency key. See timeouts and retries. When a job queue retries a failed job, each retry is a new sendMail call. Without an idempotency_key, each call gets a new random key, and the recipient can get the email twice.

So when you send from a job queue, set idempotency_key from what the email is for, such as the order and the email's name. Never use a random value or a timestamp. Each retry must also send the same message, so build the subject and content only from the job's stored data:

JavaScript
posthog: { idempotency_key: `order-${order.id}-shipped` }

When the queue owns the retries, create the transport's client with emailRequestMaxRetries: 0, so that the client doesn't also retry inside each job.

PostHog remembers a key for 24 hours after it queues the email. If a queue retries a job later than that, the same key doesn't stop a second email, so stop retrying a send after 24 hours.

Handle errors

A failed send rejects sendMail with an error that tells you if a retry can succeed:

  • error.retryable – true when sending the same message again, with the same idempotency_key, can succeed. A message without an idempotency_key is never retryable, because an earlier attempt might have queued the email. After a network error or a 503, PostHog might have queued the email too, so retry with the same key, not through another email provider.
  • error.retry_after – The number of seconds that PostHog asked you to wait, when it sent one.
  • error.code, error.status, error.detail, and error.attr – The code, HTTP status, message, and field of the error. See the errors table.

Before the send, the transport has Nodemailer read the streams and URLs in the message, such as an attachment's path. If that takes more than 60 seconds, sendMail rejects with code: "ETIMEDOUT", and PostHog sends nothing. With attachDataUrls, Nodemailer reads an html stream or URL earlier, without this limit, so give that content its own timeout.

Messages PostHog can't send

PostHog never drops the content, recipients, or options of a message. It ignores only the headers that the unsupported_header row names and the display names of every address except from, and sets its own headers. If PostHog can't carry another part of a message, sendMail rejects before the transport sends a request, and PostHog sends nothing. The error has code: "EPOSTHOGUNSUPPORTED", and error.refusal tells you why:

refusalThe message hasWhat to do
multiple_toNo to address, or more than one.Send one message for each recipient. Put copies in cc or bcc.
inline_without_cidAn inline attachment without a cid.Set cid, and use it in the HTML as <img src="cid:logo">.
unsupported_headerA custom header. PostHog ignores Message-ID (also set with messageId), Date, MIME-Version, X-Mailer, Content-Type, and Content-Transfer-Encoding, and refuses every other one. Also inReplyTo, references, list, otp, a sender that isn't the from address, or an html, text, or attachment part with its own headers.Leave the header out.
envelope_mismatchAn envelope whose addresses differ from from, to, cc, and bcc.Leave out envelope, or make it match the message.
unsupported_priorityA priority other than normal.Leave out priority.
unsupported_partAn amp, watchHtml, icalEvent, alternatives, or raw part, or a raw source for html, text, or an attachment.Send the content as html and text.
invalid_template_keyA posthog.template_key with characters other than letters, digits, hyphens, and underscores, or longer than 400 characters.Fix the key.
unsupported_optionAny other Nodemailer message option that PostHog can't apply, such as DKIM or REQUIRETLS, or any stream plugin on the transporter.Leave out the option, or remove the plugin from the transporter.

JavaScript
try {
await transporter.sendMail(message)
} catch (error) {
if (error.code === "EPOSTHOGUNSUPPORTED") {
console.error(`PostHog can't send this email: ${error.refusal}`)
}
throw error
}

Still have questions?

Was this page useful?