getmailer
v2.0.6
Published
Official Node.js SDK for GetMailer - Modern email delivery for developers
Maintainers
Readme
GetMailer Node.js SDK
Official Node.js SDK for GetMailer - Modern email delivery for developers.
Installation
npm install getmailer
# or
yarn add getmailer
# or
pnpm add getmailerQuick Start
import { GetMailer } from 'getmailer';
const client = new GetMailer({
apiKey: 'gm_xxxxx',
});
// Send an email
await client.emails.send({
from: '[email protected]',
to: '[email protected]',
subject: 'Hello from GetMailer!',
html: '<p>Welcome to GetMailer</p>',
});Features
- Full TypeScript support with strict types
- Automatic retry with exponential backoff
- Request timeout configuration
- Custom error classes for better error handling
- Idempotency key support
- Rate limit handling with automatic retry
- Debug mode for logging requests
Configuration
const client = new GetMailer({
apiKey: 'gm_xxxxx', // Required: Your API key
baseUrl: 'https://...', // Optional: Custom API base URL
timeout: 30000, // Optional: Request timeout in ms (default: 30000)
maxRetries: 3, // Optional: Max retry attempts (default: 3)
debug: false, // Optional: Enable debug logging (default: false)
});Usage Examples
Send Email
const response = await client.emails.send({
from: '[email protected]',
to: ['[email protected]', '[email protected]'],
subject: 'Hello',
html: '<h1>Welcome!</h1>',
text: 'Welcome!',
cc: '[email protected]',
bcc: '[email protected]',
replyTo: '[email protected]',
tags: ['welcome', 'onboarding'],
headers: { 'X-Custom': 'value' },
});
console.log(response.id); // Email IDSend with Template
await client.emails.sendTemplate({
from: '[email protected]',
to: '[email protected]',
templateId: 'welcome-email',
variables: {
name: 'John Doe',
url: 'https://example.com/verify',
},
});Send Batch Emails
await client.emails.sendBatch({
name: 'Weekly Newsletter',
from: '[email protected]',
templateId: 'newsletter',
recipients: [
{ to: '[email protected]', variables: { name: 'Alice' } },
{ to: '[email protected]', variables: { name: 'Bob' } },
'[email protected]',
],
});Schedule Email
await client.emails.send({
from: '[email protected]',
to: '[email protected]',
subject: 'Scheduled Email',
html: '<p>This will be sent later</p>',
scheduledAt: new Date('2024-12-25T10:00:00Z').toISOString(),
});Manage Domains
// Add a domain
const { domain } = await client.domains.add({
name: 'example.com',
});
// List domains
const { domains } = await client.domains.list();
// Verify domain
await client.domains.verify({ domainId: domain.id });
// Delete domain
await client.domains.delete(domain.id);Manage Templates
// Create template
const template = await client.templates.create({
name: 'Welcome Email',
subject: 'Welcome {{name}}!',
html: '<h1>Hello {{name}}</h1>',
});
// List templates
const { templates } = await client.templates.list();
// Get template
const tmpl = await client.templates.get(template.id);
// Update template
await client.templates.update({
id: template.id,
subject: 'Welcome {{name}} to GetMailer!',
});
// Delete template
await client.templates.delete(template.id);Manage Audiences & Contacts
// Create audience
const { audience } = await client.audiences.create({
name: 'Newsletter Subscribers',
description: 'Users who opted in for newsletters',
});
// Add contacts
await client.audiences.contacts(audience.id).add({
email: '[email protected]',
firstName: 'John',
lastName: 'Doe',
customFields: { source: 'website' },
});
// Bulk add contacts
await client.audiences.contacts(audience.id).addBulk({
contacts: [
{ email: '[email protected]', firstName: 'Alice' },
{ email: '[email protected]', firstName: 'Bob' },
],
});
// List contacts
const { contacts } = await client.audiences.contacts(audience.id).list({
limit: 50,
subscribed: true,
search: 'john',
});
// Remove contacts
await client.audiences.contacts(audience.id).remove({
emails: ['[email protected]'],
});Manage Webhooks
// Create webhook
const webhook = await client.webhooks.create({
name: 'My Webhook',
url: 'https://example.com/webhook',
events: ['SENT', 'DELIVERED', 'BOUNCED'],
});
console.log(webhook.secret); // Use this to verify webhook signatures
// List webhooks
const { webhooks } = await client.webhooks.list();
// Update webhook
await client.webhooks.update({
id: webhook.id,
enabled: false,
});
// Delete webhook
await client.webhooks.delete(webhook.id);Email Validation
// Validate single email
const result = await client.validation.verify('[email protected]');
if (result.valid) {
console.log('Email is valid');
console.log('Risk level:', result.details.risk);
}
// Batch validation
const results = await client.validation.verifyBatch([
'[email protected]',
'[email protected]',
'invalid@',
]);
console.log(`Valid: ${results.summary.valid}/${results.summary.total}`);Error Handling
import {
GetMailerError,
AuthenticationError,
RateLimitError,
ValidationError,
} from 'getmailer';
try {
await client.emails.send({ /* ... */ });
} catch (error) {
if (error instanceof AuthenticationError) {
console.error('Invalid API key');
} else if (error instanceof RateLimitError) {
console.error('Rate limited, retry after:', error.retryAfter);
} else if (error instanceof ValidationError) {
console.error('Validation error:', error.message);
} else if (error instanceof GetMailerError) {
console.error('API error:', error.status, error.message);
}
}Pagination
// List with pagination
let cursor: string | null = null;
do {
const response = await client.emails.list({
limit: 100,
cursor,
});
for (const email of response.emails) {
console.log(email.id, email.subject);
}
cursor = response.nextCursor;
} while (cursor);Idempotency
Use idempotency keys to safely retry requests:
const idempotencyKey = `email-${Date.now()}-${Math.random()}`;
await client.emails.send({
from: '[email protected]',
to: '[email protected]',
subject: 'Important Email',
html: '<p>This email will only be sent once</p>',
// Idempotency key in request headers
});API Reference
Client
new GetMailer(config)- Create a new client instance
Emails
client.emails.send(request)- Send a single emailclient.emails.sendTemplate(request)- Send email with templateclient.emails.sendBatch(request)- Send batch emailsclient.emails.get(emailId)- Get email detailsclient.emails.list(params?)- List emailsclient.emails.listBatches(params?)- List batch jobsclient.emails.getBatch(batchId)- Get batch detailsclient.emails.cancelBatch(batchId)- Cancel a batch
Domains
client.domains.list()- List all domainsclient.domains.add(request)- Add a new domainclient.domains.verify(request)- Verify domain DNS recordsclient.domains.delete(domainId)- Delete a domain
Templates
client.templates.list(params?)- List all templatesclient.templates.get(templateId)- Get template detailsclient.templates.create(request)- Create a new templateclient.templates.update(request)- Update a templateclient.templates.delete(templateId)- Delete a template
Audiences
client.audiences.list(params?)- List all audiencesclient.audiences.get(audienceId)- Get audience detailsclient.audiences.create(request)- Create a new audienceclient.audiences.delete(audienceId)- Delete an audienceclient.audiences.contacts(audienceId).list(params?)- List contactsclient.audiences.contacts(audienceId).add(contact)- Add a contactclient.audiences.contacts(audienceId).addBulk(request)- Bulk add contactsclient.audiences.contacts(audienceId).remove(request)- Remove contacts
Webhooks
client.webhooks.list()- List all webhooksclient.webhooks.create(request)- Create a new webhookclient.webhooks.update(request)- Update a webhookclient.webhooks.delete(webhookId)- Delete a webhook
Validation
client.validation.verify(email)- Validate a single emailclient.validation.verifyBatch(emails)- Validate multiple emails
TypeScript Support
The SDK is written in TypeScript and provides full type definitions:
import type {
SendEmailRequest,
EmailResponse,
Template,
Audience,
Contact,
} from 'getmailer';Error Types
GetMailerError- Base error classAuthenticationError- Invalid API key (401)RateLimitError- Rate limit exceeded (429)ValidationError- Invalid request data (400)NotFoundError- Resource not found (404)ServerError- Server error (5xx)NetworkError- Network/timeout error
License
MIT
Support
For issues and questions:
- GitHub Issues: https://github.com/getplatform/getmailer/issues
- Documentation: https://docs.getmailer.com
