npm package: @mckit/mc-mailer-sdk
Description: SDK for MC Mailer API - A Node.js library to interact with the MC Mailer service
Author: Matias Camiletti
Latest version: 1.0.2

# MC Mailer SDK for Node.js

A Node.js library for interacting with the MC Mailer API. This SDK provides a simple and convenient way to send emails and manage email operations through the MC Mailer service.

## Installation

```bash
npm install mc-mailer-sdk-nodejs
```

## Features

- Simple and intuitive API
- Configurable with API Key
- Support for sending emails
- Email status tracking
- Built-in error handling
- Promise-based async/await support

## Usage

### Basic Setup

```javascript
const MailerService = require('mc-mailer-sdk-nodejs');

// Initialize the service with your API Key and Tenant ID
const mailer = new MailerService({
  apiKey: 'your-api-key-here',
  tenantId: 'your-tenant-id-here',
  environmentId: 'your-environment-id-here' // optional
});
```

### Custom Base URL (Optional)

If you need to use a custom API endpoint:

```javascript
const mailer = new MailerService({
  apiKey: 'your-api-key-here',
  baseUrl: 'https://custom-api.mcmailer.com'
});
```

### Sending an Email

```javascript
async function sendEmail() {
  try {
    const result = await mailer.send({
      email: 'recipient@example.com',
      template: 'template-id',
      environment: 'environment-id', // optional if provided in constructor
      vars: {
        key: 'value'
      },
      attachments: [
        {
          filename: 'example.pdf',
          content: 'base64-encoded-content-here',
          contentType: 'application/pdf'
        }
      ]
    });
    
    console.log('Email sent successfully:', result);
  } catch (error) {
    console.error('Failed to send email:', error.message);
  }
}

sendEmail();
```

### Checking Email Status

```javascript
async function checkStatus(emailId) {
  try {
    const status = await mailer.getEmailStatus(emailId);
    console.log('Email status:', status);
  } catch (error) {
    console.error('Failed to get status:', error.message);
  }
}

checkStatus('email-id-123');
```

### Making Custom API Calls

For custom API endpoints:

```javascript
async function customRequest() {
  try {
    const result = await mailer.request('/custom/endpoint', {
      method: 'POST',
      body: {
        // your data here
      },
      headers: {
        // additional headers if needed
      }
    });
    
    console.log('Response:', result);
  } catch (error) {
    console.error('Request failed:', error.message);
  }
}
```

## API Reference

### Constructor

```javascript
new MailerService(config)
```

**Parameters:**
- `config` (Object) - Configuration object
  - `apiKey` (string, required) - Your API Key for authentication
  - `tenantId` (string, required) - Your Tenant ID for authentication
  - `environmentId` (string, optional) - Default Environment ID
  - `baseUrl` (string, optional) - Custom base URL for the API

### Methods

#### `send(emailData)`

Sends an email through the MC Mailer API.

**Parameters:**
- `emailData` (Object)
  - `email` (string, required) - Recipient email address
  - `template` (string, required) - Template ID
  - `environment` (string, required) - Environment ID (can be omitted if provided in constructor)
  - `vars` (Object, optional) - Variables to be used in the template
  - `attachments` (Array<Object>, optional) - Attachments to include in the email

**Returns:** Promise<Object> - API response

#### `getEmailStatus(emailId)`

Gets the status of a sent email.

**Parameters:**
- `emailId` (string, required) - Email ID

**Returns:** Promise<Object> - Email status information

#### `request(endpoint, options)`

Makes a custom HTTP request to the API.

**Parameters:**
- `endpoint` (string, required) - API endpoint path
- `options` (Object, optional)
  - `method` (string) - HTTP method (default: 'GET')
  - `body` (Object) - Request body for POST/PUT requests
  - `headers` (Object) - Additional headers

**Returns:** Promise<Object> - API response

## Error Handling

The SDK throws errors in the following cases:

1. **Missing API Key:** When initializing without an API Key
2. **Network Errors:** When unable to reach the API
3. **API Errors:** When the API returns an error response

Example error handling:

```javascript
try {
  const result = await mailer.sendEmail(emailData);
} catch (error) {
  if (error.status) {
    // API error with status code
    console.error(`API Error ${error.status}:`, error.response);
  } else {
    // Network or other error
    console.error('Error:', error.message);
  }
}
```

## Requirements

- **Node.js 18.0.0 or higher** (required for native fetch API support)

The library uses the native fetch API that is built into Node.js 18+. If you need to use this library with an older version of Node.js, you would need to install a fetch polyfill:

```bash
npm install node-fetch
```

And modify the import in `lib/MailerService.js` to use the polyfill. However, we recommend using Node.js 18+ for the best experience.

## License

MIT

## Author

Matias Camiletti

## Repository

https://github.com/matiascamiletti/mc-mailer-sdk-nodejs