Email API

Send transactional and marketing emails with the Metigan Email API. Supports HTML content, attachments, templates, tracking, and more. Built for reliability, scalability, and developer experience.

Overview

The Email API allows you to send emails through Metigan's infrastructure. All emails are sent using the metigan.email.sendEmail() method, which provides a simple, consistent interface for all your email sending needs.

Basic Usage

Here's a simple example of sending an email using the Metigan Email API:

basic-email.tsTypeScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import Metigan from 'metigan';
import type { EmailApiResponse, EmailSuccessResponse } from 'metigan';

const metigan = new Metigan({
  apiKey: 'your_api_key'
});

// Type guard for type safety
function isEmailSuccess(response: EmailApiResponse): response is EmailSuccessResponse {
  return 'success' in response && response.success === true;
}

// Send a basic email
async function sendEmail() {
  const result = await metigan.email.sendEmail({
    from: 'Sender Name <sender@example.com>',
    recipients: ['recipient@example.com'],
    subject: 'Hello from Metigan!',
    content: '<h1>Hello!</h1><p>This is a test email.</p>'
  });

  // Check result with type guard
  if (isEmailSuccess(result)) {
    console.log('✅ Email sent successfully!');
    console.log('Tracking ID:', result.successfulEmails[0]?.trackingId);
    console.log('Emails remaining:', result.emailsRemaining);
  } else {
    console.error('❌ Failed to send:', result.message || result.error);
  }
}

sendEmail();

Parameters

ParameterTypeRequiredDescription
fromstringYesSender email address. Can be formatted as "Name <email@example.com>" or just "email@example.com"
recipientsstring[]YesArray of recipient email addresses
subjectstringYesEmail subject line
contentstringYes*HTML email content. Required if templateId is not provided
templateIdstringNoID of a pre-created email template to use instead of content
ccstring[]NoArray of CC recipient email addresses
bccstring[]NoArray of BCC recipient email addresses
replyTostringNoReply-to email address
attachmentsArray<File | NodeAttachment | CustomAttachment>NoArray of file attachments

Examples

basic-email.tsTypeScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import Metigan from 'metigan';

const metigan = new Metigan({
  apiKey: 'your_api_key'
});

// Send a simple HTML email
const result = await metigan.email.sendEmail({
  from: 'hello@example.com',
  recipients: ['user@example.com'],
  subject: 'Welcome!',
  content: `
    <!DOCTYPE html>
    <html>
      <body>
        <h1>Welcome to Our Service!</h1>
        <p>Thank you for signing up.</p>
      </body>
    </html>
  `
});

Response Format

The sendEmail method returns an EmailApiResponse which can be one of three types:

success-response.tsTypeScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// EmailSuccessResponse
{
  success: true,
  message: "Email sent successfully",
  successfulEmails: [
    {
      recipient: "user@example.com",
      trackingId: "track_abc123"
    }
  ],
  failedEmails: [],
  recipientCount: 1,
  emailsRemaining: 9999
}
Type Safety

Use the isEmailSuccess() type guard or check for the success property to narrow the response type safely.

Using Email Templates

Templates allow you to reuse email designs and content. You can create templates in your Metigan dashboard or programmatically using the Templates API.

Creating Templates

Create templates using the Templates API or in your dashboard. Templates support variables using double curly braces: {{variableName}}

create-template.tsTypeScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import Metigan from 'metigan';

const metigan = new Metigan({
  apiKey: 'your_api_key'
});

// Create a reusable email template
const template = await metigan.templates.create({
  name: 'Welcome Email Template',
  subject: 'Welcome to Our Service, {{firstName}}!',
  content: `
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
      </head>
      <body style="font-family: Arial, sans-serif; padding: 20px; max-width: 600px; margin: 0 auto;">
        <h1 style="color: #2563eb;">Welcome, {{firstName}}!</h1>
        <p>Thank you for signing up, {{firstName}} {{lastName}}.</p>
        <p>Your email address is: <strong>{{email}}</strong></p>
        
        <div style="margin-top: 30px; padding: 20px; background-color: #f3f4f6; border-radius: 8px;">
          <p>To get started, please click the button below:</p>
          <a href="{{activationLink}}" 
             style="display: inline-block; padding: 12px 24px; background-color: #2563eb; color: white; 
                    text-decoration: none; border-radius: 6px; margin-top: 10px;">
            Activate Account
          </a>
        </div>
        
        <p style="margin-top: 30px; color: #6b7280; font-size: 14px;">
          If you didn't create this account, please ignore this email.
        </p>
      </body>
    </html>
  `
});

console.log('Template created with ID:', template.id);
// Save this templateId for later use

Sending Emails with Templates

Once you have a template ID, you can send emails using that template. The template's subject and content will be used, and variables will be replaced automatically if configured in your template settings.

send-with-template.tsTypeScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import Metigan from 'metigan';
import type { EmailApiResponse, EmailSuccessResponse } from 'metigan';

const metigan = new Metigan({
  apiKey: 'your_api_key'
});

function isEmailSuccess(response: EmailApiResponse): response is EmailSuccessResponse {
  return 'success' in response && response.success === true;
}

async function sendWelcomeEmail() {
  try {
    const result = await metigan.email.sendEmail({
      from: 'Welcome Team <welcome@example.com>',
      recipients: ['newuser@example.com'],
      subject: 'Welcome to Our Service, John!', // Optional: override template subject
      templateId: 'your_template_id_here', // Template ID from dashboard or API
      // Template variables like {{firstName}}, {{lastName}}, {{email}}, {{activationLink}}
      // should be configured in your template settings or passed via template API
    });

    if (isEmailSuccess(result)) {
      console.log('✅ Welcome email sent successfully!');
      console.log('Tracking ID:', result.successfulEmails[0]?.trackingId);
    } else {
      console.error('❌ Failed to send email:', result.message || result.error);
    }
  } catch (error) {
    console.error('Error sending email:', error);
  }
}

sendWelcomeEmail();

Template Variables

Templates support variables using the {{variableName}} syntax. Common variables include:

VariableExampleDescription
{{firstName}}JohnUser's first name
{{lastName}}DoeUser's last name
{{email}}user@example.comUser's email address
{{activationLink}}https://...Dynamic link for activation
Variable Configuration

Template variables are typically configured when creating the template or can be passed when sending. Check the Templates API documentation for more details on managing template variables.