Skip to content

Official Node.js SDK for GetMailer - Modern email delivery for developers

Notifications You must be signed in to change notification settings

getplatform/getmailer-node

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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 getmailer

Quick Start

import { GetMailer } from 'getmailer';

const client = new GetMailer({
  apiKey: 'gm_xxxxx',
});

// Send an email
await client.emails.send({
  from: 'hello@example.com',
  to: 'user@example.com',
  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: 'hello@example.com',
  to: ['user1@example.com', 'user2@example.com'],
  subject: 'Hello',
  html: '<h1>Welcome!</h1>',
  text: 'Welcome!',
  cc: 'cc@example.com',
  bcc: 'bcc@example.com',
  replyTo: 'reply@example.com',
  tags: ['welcome', 'onboarding'],
  headers: { 'X-Custom': 'value' },
});

console.log(response.id); // Email ID

Send with Template

await client.emails.sendTemplate({
  from: 'hello@example.com',
  to: 'user@example.com',
  templateId: 'welcome-email',
  variables: {
    name: 'John Doe',
    url: 'https://example.com/verify',
  },
});

Send Batch Emails

await client.emails.sendBatch({
  name: 'Weekly Newsletter',
  from: 'news@example.com',
  templateId: 'newsletter',
  recipients: [
    { to: 'user1@example.com', variables: { name: 'Alice' } },
    { to: 'user2@example.com', variables: { name: 'Bob' } },
    'user3@example.com',
  ],
});

Schedule Email

await client.emails.send({
  from: 'hello@example.com',
  to: 'user@example.com',
  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: 'user@example.com',
  firstName: 'John',
  lastName: 'Doe',
  customFields: { source: 'website' },
});

// Bulk add contacts
await client.audiences.contacts(audience.id).addBulk({
  contacts: [
    { email: 'user1@example.com', firstName: 'Alice' },
    { email: 'user2@example.com', 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: ['user@example.com'],
});

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('user@example.com');

if (result.valid) {
  console.log('Email is valid');
  console.log('Risk level:', result.details.risk);
}

// Batch validation
const results = await client.validation.verifyBatch([
  'user1@example.com',
  'user2@example.com',
  '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: 'hello@example.com',
  to: 'user@example.com',
  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 email
  • client.emails.sendTemplate(request) - Send email with template
  • client.emails.sendBatch(request) - Send batch emails
  • client.emails.get(emailId) - Get email details
  • client.emails.list(params?) - List emails
  • client.emails.listBatches(params?) - List batch jobs
  • client.emails.getBatch(batchId) - Get batch details
  • client.emails.cancelBatch(batchId) - Cancel a batch

Domains

  • client.domains.list() - List all domains
  • client.domains.add(request) - Add a new domain
  • client.domains.verify(request) - Verify domain DNS records
  • client.domains.delete(domainId) - Delete a domain

Templates

  • client.templates.list(params?) - List all templates
  • client.templates.get(templateId) - Get template details
  • client.templates.create(request) - Create a new template
  • client.templates.update(request) - Update a template
  • client.templates.delete(templateId) - Delete a template

Audiences

  • client.audiences.list(params?) - List all audiences
  • client.audiences.get(audienceId) - Get audience details
  • client.audiences.create(request) - Create a new audience
  • client.audiences.delete(audienceId) - Delete an audience
  • client.audiences.contacts(audienceId).list(params?) - List contacts
  • client.audiences.contacts(audienceId).add(contact) - Add a contact
  • client.audiences.contacts(audienceId).addBulk(request) - Bulk add contacts
  • client.audiences.contacts(audienceId).remove(request) - Remove contacts

Webhooks

  • client.webhooks.list() - List all webhooks
  • client.webhooks.create(request) - Create a new webhook
  • client.webhooks.update(request) - Update a webhook
  • client.webhooks.delete(webhookId) - Delete a webhook

Validation

  • client.validation.verify(email) - Validate a single email
  • client.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 class
  • AuthenticationError - 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:

About

Official Node.js SDK for GetMailer - Modern email delivery for developers

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •