Docs/JavaScript SDK

JavaScript SDK

@sendmailos/sdk

Official TypeScript SDK for SendMailOS. Type-safe, lightweight, with React components included.

Type-Safe

Full TypeScript support with exported types

Lightweight

Zero dependencies for core SDK

React Ready

Pre-built hooks and components

Installation

bash
npm install @sendmailos/sdk

Quick Start

Initialize the client with your API key. Find your key in Dashboard → Settings → API Keys.

typescript
import { SendMailOS } from '@sendmailos/sdk';

// Initialize with your API key
const client = new SendMailOS('sk_live_your_api_key');

// Or use environment variables (recommended)
const client = new SendMailOS(process.env.SENDMAILOS_API_KEY!);

Security Warning

Never expose secret keys (sk_*) in client-side code. Use the SDK in server-side environments only (Node.js, Next.js API routes, serverless functions).

Send Emails

client.emails.send()

Send transactional emails with HTML content or templates.

typescript
const result = await client.emails.send({
  to: '[email protected]',
  fromName: 'Your Company',
  fromEmail: '[email protected]',
  subject: 'Welcome aboard!',
  html: '<h1>Hello!</h1><p>Welcome to our platform.</p>'
});

console.log('Email queued:', result.id);

Attachment Limits

Max 5 attachments per email • Max 5MB per file • Max 7MB total • Supports URL or Base64 content

Manage Subscribers

client.subscribers.create()

Add or update subscribers with automatic deduplication.

typescript
// Create a new subscriber
const { subscriber } = await client.subscribers.create({
  email: '[email protected]',
  firstName: 'John',
  lastName: 'Doe',
  tags: ['newsletter', 'premium']
});

console.log('Subscriber ID:', subscriber.id);

client.subscribers.list()

typescript
// List subscribers with pagination
const { subscribers, total } = await client.subscribers.list({
  limit: 50,
  offset: 0
});

console.log(`Found ${total} subscribers`);

Send Campaigns

Send bulk email campaigns to subscribers filtered by tags.

typescript
const result = await client.campaigns.send({
  name: 'January Newsletter',
  subject: '{{first_name}}, check out what\'s new!',
  fromName: 'Your Company',
  fromEmail: '[email protected]',
  html: '<h1>Hi {{first_name}}!</h1><p>Here are this month\'s updates...</p>',
  tags: ['newsletter', 'active']  // Only subscribers with BOTH tags
});

console.log(`Campaign queued: ${result.campaignId}`);

React Components

The SDK includes React components for common email marketing patterns.

SendMailOSProvider

Wrap your app with the provider to enable the SDK context.

tsx
import { SendMailOSProvider } from '@sendmailos/sdk/react';

function App() {
  return (
    <SendMailOSProvider publicKey="pk_live_your_public_key">
      <YourApp />
    </SendMailOSProvider>
  );
}

SubscribeForm

Pre-built newsletter subscription form with customization options.

tsx
import { SubscribeForm } from '@sendmailos/sdk/react';

function NewsletterSignup() {
  return (
    <SubscribeForm
      tags={['newsletter']}
      onSuccess={() => console.log('Subscribed!')}
      onError={(err) => console.error(err)}
      buttonText="Join Newsletter"
      placeholder="Enter your email"
      showNameFields={true}
    />
  );
}

useSubscribe Hook

Build custom forms with the useSubscribe hook.

tsx
import { useSubscribe } from '@sendmailos/sdk/react';
import { useState } from 'react';

function CustomForm() {
  const { subscribe, isLoading, error, isSuccess } = useSubscribe();
  const [email, setEmail] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    await subscribe({ email, tags: ['newsletter'] });
  };

  if (isSuccess) return <p>Thanks for subscribing!</p>;

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        placeholder="Enter your email"
      />
      <button disabled={isLoading}>
        {isLoading ? 'Subscribing...' : 'Subscribe'}
      </button>
      {error && <p className="error">{error.message}</p>}
    </form>
  );
}

Webhook Verification

Verify webhook signatures to ensure requests came from SendMailOS.

typescript
import { verifyWebhookSignature } from '@sendmailos/sdk';

// Next.js API Route example
export async function POST(request: Request) {
  const payload = await request.text();
  const signature = request.headers.get('x-sendmailos-signature')!;
  const timestamp = request.headers.get('x-sendmailos-timestamp')!;

  const isValid = verifyWebhookSignature({
    payload,
    signature,
    timestamp,
    secret: process.env.WEBHOOK_SECRET!
  });

  if (!isValid) {
    return new Response('Invalid signature', { status: 401 });
  }

  const event = JSON.parse(payload);

  switch (event.type) {
    case 'email.delivered':
      console.log('Email delivered to:', event.data.recipient);
      break;
    case 'email.bounced':
      console.log('Email bounced:', event.data.recipient);
      break;
  }

  return new Response('OK', { status: 200 });
}

Error Handling

The SDK provides custom error classes for different scenarios.

typescript
import {
  SendMailOS,
  SendMailOSError,
  RateLimitError,
  AuthenticationError
} from '@sendmailos/sdk';

try {
  await client.emails.send({ ... });
} catch (error) {
  if (error instanceof RateLimitError) {
    // Retry after the specified time
    console.log(`Rate limited. Retry after ${error.retryAfter} seconds`);
  } else if (error instanceof AuthenticationError) {
    // Invalid API key
    console.log('Check your API key');
  } else if (error instanceof SendMailOSError) {
    // Other API errors
    console.log(`Error: ${error.message} (code: ${error.code})`);

    if (error.isRetryable) {
      // Safe to retry (rate limit or server error)
    }
  }
}

TypeScript Types

All types are exported for full type safety.

typescript
import type {
  // Client
  SendMailOSOptions,

  // Email
  SendEmailRequest,
  SendEmailResponse,
  EmailAttachment,

  // Subscriber
  Subscriber,
  CreateSubscriberRequest,
  ListSubscribersResponse,

  // Campaign
  SendCampaignRequest,
  SendCampaignResponse,

  // Domain
  Domain,
  DnsRecord,

  // Webhook
  WebhookEvent,
  WebhookEventType
} from '@sendmailos/sdk';

Related Resources