X Enterprises
fastify-xemail

sendTemplate

Send an email using a SendGrid dynamic template.

sendTemplate

Send an email using a SendGrid dynamic template. The subject is automatically injected into dynamicTemplateData so template subject lines can reference {{subject}}.

Signature

fastify.xEmail.sendTemplate(
  to: string | string[],
  subject: string,
  templateId: string,
  dynamicData?: object,
  extraOptions?: object
): Promise<{ success: boolean; statusCode: number; messageId: string }>

Params

NameTypeRequiredDescription
tostring | string[]YesRecipient email address or array of addresses.
subjectstringYesEmail subject line. Also injected as subject in dynamicTemplateData.
templateIdstringYesSendGrid dynamic template ID (starts with d-).
dynamicDataobjectNoTemplate variable substitutions (e.g., { firstName: "Tim", actionUrl: "..." }).
extraOptionsobjectNoAdditional SendGrid mail options merged into the message.

Returns

Promise<{ success: boolean; statusCode: number; messageId: string }>

PropertyTypeDescription
successbooleanAlways true on resolved promise.
statusCodenumberSendGrid HTTP response status (typically 202).
messageIdstringSendGrid message ID from the x-message-id response header.

Throws

  • [xEmail] 'to' is required for sendTemplate(). — missing recipient.
  • [xEmail] 'subject' is required for sendTemplate(). — missing subject.
  • [xEmail] 'templateId' is required for sendTemplate(). — missing template ID.
  • [xEmail] Failed to send template email: <reason> — SendGrid API error.

Examples

Basic — welcome email via template

fastify.post("/auth/register", async (request, reply) => {
  const user = await createUser(request.body);

  await fastify.xEmail.sendTemplate(
    user.email,
    "Welcome to My App",
    "d-abc123def456",
    { firstName: user.firstName, dashboardUrl: "https://app.example.com/dashboard" }
  );

  return { userId: user.id };
});

Realistic — order confirmation with multiple data fields

fastify.post("/orders/:id/confirm", async (request, reply) => {
  const order = await db.orders.findById(request.params.id);

  await fastify.xEmail.sendTemplate(
    order.customerEmail,
    `Order Confirmed — #${order.orderNumber}`,
    process.env.ORDER_CONFIRM_TEMPLATE_ID,
    {
      orderNumber: order.orderNumber,
      items: order.items,
      total: order.total,
      estimatedDelivery: order.estimatedDelivery,
      trackingUrl: `https://app.example.com/orders/${order.id}/track`,
    }
  );

  return { confirmed: true };
});

See Also

AI Context

package: "@xenterprises/fastify-xemail"
method: fastify.xEmail.sendTemplate(to, templateId, dynamicData, options?)
use-when: Send an email using a SendGrid dynamic template with variable substitution
params: to (string), templateId (string), dynamicData (object), options (from, subject override, cc, bcc)
returns: Promise<void>
Copyright © 2026