Email Sending

Document information
  • Canonical URL: /docs/03_writing-step-code/15_email-sending
  • Version: 2026-11-26
  • Tags: code-snippets, email, reference, processflow

ProcessFlow steps send mail through the sandbox helper tf.email.send (also available as root global email.send when the api capability is enabled). The helper validates the recipient, queues delivery via POST /api/v1/processflow?action=send-email, and returns queue fields the next step can inspect. Prefer one deterministic send per step over silent multi-send loops.

Canonical surface: Process sandbox tf API. Agent contract: skill_id platform-code-generation → process-step-runtime.md / describe_process_step_code_contract.

Email sending pipeline showing recipient validation, template rendering, queue submission, and delivery tracking for ProcessFlow steps.

Call shape

await tf.email.send({
  to: "ops@example.com",    // string, string[], or "a@x.com, b@y.com"
  cc: "audit@example.com",  // optional
  bcc: ["archive@example.com"],
  subject: "Subject line",
  text: "Plain body",       // and/or html: "<p>HTML body</p>"
  process_id: undefined,    // optional; defaults to the running process
  metadata: {}              // optional plain object
});

Rules enforced by the sandbox:

  • to, subject, and at least one of text / html are required. cc and bcc are optional.
  • A string to with one address is the same call existing steps already use.
  • to, cc, and bcc each accept a string or an array of strings. A string that is not itself one address may list several addresses separated by commas or semicolons.
  • Each address is a plain mailbox (ops@example.com). Characters <>"' are rejected, so display names such as Ops <ops@example.com> are rejected.
  • One call queues one message. Addresses on to and cc are visible to those recipients. bcc is omitted from the message headers they see.
  • The same address is kept on the first field that lists it, in order to, then cc, then bcc.
  • At most 50 addresses across to, cc, and bcc.
  • Subject and body size limits apply (see runtime / validator errors).
  • On success, the result includes queue fields such as queue_id, status, and enqueued. One queue id covers the whole recipient set.
  • On failure, the helper throws (or the Nest action returns success: false).
const queued = await tf.email.send({
  to: ["ops@example.com", "lead@example.com"],
  cc: "audit@example.com",
  bcc: "archive@example.com",
  subject: "Shared alert",
  text: "The same body goes to every recipient."
});

Do not use legacy positional helpers such as email.sendEmail(to, subject, html) in ProcessFlow step code — that API is not the current sandbox contract.

Start with a safe single-email pattern

Validate inputs, call tf.email.send, and return explicit queue status fields.

const to = String(process_input.result?.to ?? "").trim();
const subject = String(process_input.result?.subject ?? "").trim();
const body = String(process_input.result?.body ?? "");
const isHtml = Boolean(process_input.result?.is_html ?? false);

if (to === "" || subject === "" || body === "") {
  return { success: false, error: "Missing required fields: to, subject, body" };
}

if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(to)) {
  return { success: false, error: "Invalid email address" };
}

const payload = isHtml
  ? { to, subject, html: body }
  : { to, subject, text: body };

const queued = await tf.email.send(payload);

return {
  success: true,
  data: {
    recipient: to,
    subject,
    queue_id: queued.queue_id ?? null,
    status: queued.status ?? null,
    enqueued: queued.enqueued ?? null
  }
};

Render templates with explicit placeholders

Keep templates on a small allowlist and only replace known keys.

const to = String(process_input.result?.to ?? "").trim();
const subject = String(process_input.result?.subject ?? "").trim();
const templateName = String(process_input.result?.template ?? "default");
const templateData = (process_input.result?.template_data ?? {}) as Record<string, unknown>;

const templates: Record<string, string> = {
  welcome: "<h1>Welcome, {{name}}!</h1><p>Sign in: <a href=\"{{login_url}}\">{{login_url}}</a></p>",
  alert: "<h2>{{title}}</h2><p>{{message}}</p><p>{{timestamp}}</p>",
  default: "<p>{{content}}</p>"
};

let htmlBody = templates[templateName] ?? templates.default;

for (const [key, value] of Object.entries(templateData)) {
  htmlBody = htmlBody.replaceAll(`{{${key}}}`, String(value ?? ""));
}

if (to === "" || subject === "") {
  return { success: false, error: "Missing required fields: to, subject" };
}

const queued = await tf.email.send({ to, subject, html: htmlBody });

return {
  success: true,
  data: {
    recipient: to,
    template: templateName,
    queue_id: queued.queue_id ?? null,
    enqueued: queued.enqueued ?? null
  }
};

Handle batches without losing per-recipient visibility

Use one tf.email.send with several to / cc / bcc addresses when every person should receive the same body. Use the loop below when each person needs a different subject or body, or when the step must report which address was queued. Validate each address, send one message at a time, and return sent / failed / invalid lists.

const recipients = (process_input.result?.recipients ?? []) as unknown[];
const subjectTemplate = String(process_input.result?.subject ?? "");
const bodyTemplate = String(process_input.result?.body_template ?? "");
const results: {
  sent: string[];
  failed: Array<{ email: string; error: string }>;
  invalid: Array<{ email: string; error: string }>;
} = { sent: [], failed: [], invalid: [] };

for (const recipient of recipients) {
  const isObject = recipient != null && typeof recipient === "object" && !Array.isArray(recipient);
  const address = isObject
    ? String((recipient as Record<string, unknown>).email ?? "").trim()
    : String(recipient ?? "").trim();
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(address)) {
    results.invalid.push({ email: address, error: "Invalid email format" });
    continue;
  }

  const data = isObject ? (recipient as Record<string, unknown>) : { email: recipient };
  let subject = subjectTemplate;
  let body = bodyTemplate;
  for (const [key, value] of Object.entries(data)) {
    subject = subject.replaceAll(`{{${key}}}`, String(value ?? ""));
    body = body.replaceAll(`{{${key}}}`, String(value ?? ""));
  }

  try {
    const queued = await tf.email.send({ to: address, subject, text: body });
    if (queued && (queued.enqueued === true || queued.success === true || queued.queue_id)) {
      results.sent.push(address);
    } else {
      results.failed.push({ email: address, error: "Queue rejected" });
    }
  } catch (err) {
    results.failed.push({
      email: address,
      error: err instanceof Error ? err.message : "Send failed"
    });
  }
}

return {
  success: results.failed.length === 0 && results.invalid.length === 0,
  data: {
    total_recipients: recipients.length,
    sent_count: results.sent.length,
    failed_count: results.failed.length,
    invalid_count: results.invalid.length,
    results
  }
};

External HTTP email APIs

If you call a third-party or custom HTTP mail API instead of tf.email.send, use tf.api or a connector with tenant-scoped credentials. Do not hard-code API keys in step snippets. The examples above are the supported platform path for ProcessFlow.

See also