Spanish Total.js
English
Documentation For AI agents
Contents

Send from Node.js

A small Node.js function that sends an email through OpenMail and reports errors.

.md GitHub
On this page

This recipe sends the demo/welcome template from a Node.js app with the built-in fetch. It needs no extra package.

The code

Save it as send.mjs:

// send.mjs: sends the "demo/welcome" email through OpenMail.
const OPENMAIL = process.env.OPENMAIL_URL;
const TOKEN = process.env.OPENMAIL_TOKEN;

async function sendmail(id, to, data) {
    const response = await fetch(OPENMAIL + '/', {
        method: 'POST',
        headers: { 'content-type': 'application/json', 'x-token': TOKEN },
        body: JSON.stringify({ id, to, data }),
        signal: AbortSignal.timeout(30000)
    });
    const body = await response.json();
    if (!response.ok)
        throw new Error(response.status + ' ' + JSON.stringify(body));
    return body;
}

console.log(await sendmail('demo/welcome', 'jane@example.com', { name: 'Jane Doe', plan: 'Pro' }));

try {
    await sendmail('demo/missing', 'jane@example.com', {});
} catch (e) {
    console.log(e.message);
}

Run it

OPENMAIL_URL=https://mail.example.com OPENMAIL_TOKEN=YOUR_TOKEN node send.mjs

The output:

{ success: true }
400 [{"error":"Template not found"}]

The first email is sent; the second call fails because the template demo/missing does not exist.

Notes

  • The timeout stops the request after 30 seconds if the SMTP server does not respond.
  • A wrong token answers 401 with an HTML page, so response.json() throws. Check the token if you see a JSON parse error. See Errors.
  • Keep the token on the server. Never put it in code that runs in the browser.
Made in Europe