@xenterprises/fastify-xemail
v1.1.1
Published
Fastify plugin for SendGrid email integration — transactional emails, templates, bulk sending, validation, and contact management.
Readme
@xenterprises/fastify-xemail
Fastify plugin for SendGrid email — send transactional emails, template emails, bulk messages, validate addresses, and manage marketing contacts and lists.
Installation
npm install @xenterprises/fastify-xemailUsage
import Fastify from 'fastify';
import xEmail from '@xenterprises/fastify-xemail';
const fastify = Fastify();
await fastify.register(xEmail, {
apiKey: process.env.SENDGRID_API_KEY,
fromEmail: process.env.SENDGRID_FROM_EMAIL,
fromName: 'My App', // optional
});
// Send a simple email
await fastify.xEmail.send(
'[email protected]',
'Welcome!',
'<h1>Welcome!</h1><p>Thanks for signing up.</p>'
);Options
| Name | Type | Default | Required | Description |
|------|------|---------|----------|-------------|
| apiKey | string | — | Yes | SendGrid API key |
| fromEmail | string | — | Yes | Verified sender email address |
| fromName | string | — | No | Sender display name |
| active | boolean | true | No | Set false to disable the plugin entirely |
Decorated Methods
All methods are available on fastify.xEmail.
send(to, subject, html, text?, extraOptions?)
Send an email. Plain text is auto-generated from HTML if omitted.
const result = await fastify.xEmail.send('[email protected]', 'Hello', '<p>Hi</p>');
// { success: true, statusCode: 202, messageId: 'xxx' }sendTemplate(to, subject, templateId, dynamicData?, extraOptions?)
Send using a SendGrid dynamic template.
await fastify.xEmail.sendTemplate(
'[email protected]',
'Welcome',
'd-abc123def456',
{ firstName: 'Tim', actionUrl: 'https://example.com/verify' }
);sendWithAttachments(to, subject, html, attachments)
Send an email with file attachments. Each attachment needs content (base64), filename, and type (MIME).
await fastify.xEmail.sendWithAttachments(
'[email protected]',
'Your Invoice',
'<p>See attached.</p>',
[{ content: base64String, filename: 'invoice.pdf', type: 'application/pdf' }]
);sendBulk(to, subject, html)
Send the same email to multiple recipients at once.
await fastify.xEmail.sendBulk(
['[email protected]', '[email protected]'],
'Announcement',
'<p>Big news!</p>'
);
// { success: true, count: 2, statusCode: 202 }sendPersonalizedBulk(messages)
Send different content to each recipient. Returns per-recipient results including partial failures.
const results = await fastify.xEmail.sendPersonalizedBulk([
{ to: '[email protected]', subject: 'Hi A', html: '<p>Hello A</p>' },
{ to: '[email protected]', subject: 'Hi B', html: '<p>Hello B</p>' },
]);
// [{ success: true, to: '[email protected]', statusCode: 202 }, ...]validate(email)
Validate an email address using the SendGrid Email Validation API. Returns a soft result on API errors instead of throwing.
const result = await fastify.xEmail.validate('[email protected]');
// { email: '...', valid: true, verdict: 'Valid', score: 0.95, result: {...} }addContact(email, data?, listIds?)
Add or update a contact in SendGrid Marketing. Accepts both firstName/lastName and first_name/last_name.
await fastify.xEmail.addContact('[email protected]', {
firstName: 'Tim',
lastName: 'Smith',
customFields: { w1_T: 'premium' }
}, ['list-id-1']);
// { success: true, jobId: '...', email: '...' }searchContact(email)
Search for a contact by email.
const result = await fastify.xEmail.searchContact('[email protected]');
// { found: true, contact: { id: '...', email: '...', ... } }deleteContact(contactId)
Delete a contact by ID. Returns true on success.
createList(name)
Create a new marketing contact list.
const result = await fastify.xEmail.createList('Newsletter');
// { success: true, list: { id: '...', name: 'Newsletter' } }getLists()
Get all contact lists. Returns an array.
deleteList(listId)
Delete a contact list by ID. Returns true on success.
Environment Variables
| Name | Required | Description |
|------|----------|-------------|
| SENDGRID_API_KEY | Yes | SendGrid API key with Mail Send permissions |
| SENDGRID_FROM_EMAIL | Yes | Verified sender email address |
| SENDGRID_FROM_NAME | No | Sender display name |
Error Reference
All errors are prefixed with [xEmail] for easy identification in logs.
| Error | When |
|-------|------|
| [xEmail] 'apiKey' (string) is required. | Missing or non-string apiKey at registration |
| [xEmail] 'fromEmail' (string) is required. | Missing or non-string fromEmail at registration |
| [xEmail] 'to' is required for send(). | Calling send() without a recipient |
| [xEmail] 'subject' is required for send(). | Calling send() without a subject |
| [xEmail] 'html' is required for send(). | Calling send() without HTML content |
| [xEmail] 'templateId' is required for sendTemplate(). | Missing template ID |
| [xEmail] 'attachments' must be a non-empty array. | Empty or non-array attachments |
| [xEmail] 'to' must be a non-empty array for sendBulk(). | Non-array or empty array for bulk |
| [xEmail] 'messages' must be a non-empty array for sendPersonalizedBulk(). | Empty messages array |
| [xEmail] 'email' (string) is required for validate(). | Missing email for validation |
| [xEmail] Failed to send email: <reason> | SendGrid API rejection on send |
| [xEmail] Failed to add contact: <reason> | SendGrid API rejection on contact add |
How It Works
The plugin initializes both @sendgrid/mail (for transactional emails) and @sendgrid/client (for the Marketing and Validation APIs) with the provided API key. It decorates the Fastify instance with fastify.xEmail, an object containing all email and contact management methods.
Each method validates its required parameters before making any API call. Transactional methods (send, sendTemplate, sendWithAttachments, sendBulk) use sgMail, while marketing and validation methods (validate, addContact, searchContact, deleteContact, createList, getLists, deleteList) use sgClient with direct REST calls.
Errors from SendGrid are caught, logged via fastify.log.error (with structured error objects, never credentials), and re-thrown with a descriptive [xEmail] prefix. The validate() method is an exception — it returns a soft error result instead of throwing, since validation failures are expected in normal operation.
Setting active: false causes the plugin to return immediately without decorating, which is useful for disabling email in test environments.
License
UNLICENSED
