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
| Name | Type | Required | Description |
|---|---|---|---|
to | string | string[] | Yes | Recipient email address or array of addresses. |
subject | string | Yes | Email subject line. Also injected as subject in dynamicTemplateData. |
templateId | string | Yes | SendGrid dynamic template ID (starts with d-). |
dynamicData | object | No | Template variable substitutions (e.g., { firstName: "Tim", actionUrl: "..." }). |
extraOptions | object | No | Additional SendGrid mail options merged into the message. |
Returns
Promise<{ success: boolean; statusCode: number; messageId: string }>
| Property | Type | Description |
|---|---|---|
success | boolean | Always true on resolved promise. |
statusCode | number | SendGrid HTTP response status (typically 202). |
messageId | string | SendGrid 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
- send — Send with inline HTML instead of a template
- send-personalized-bulk — Send different template data per recipient
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>
