npm package: @fourtwentydev/mailservice
Description: A lightweight client for the FourTwenty Email Service API
Author: FourTwentyDevs
Latest version: 1.0.2

# FourTwenty Email Service Client

A lightweight, easy-to-use client for the [FourTwenty Email Service](https://mailservice.fourtwenty.dev) API.

## Features

- 📧 Simple email sending with plain text and HTML support
- 📎 File attachment support
- 🔄 Automatic retries with configurable backoff strategies
- ⚠️ Comprehensive error handling
- 🔒 TypeScript support with full type definitions
- 🌐 Works in both Node.js and browser environments

## Installation

```bash
npm install @fourtwentydev/mailservice
```

## Quick Start

### Function-based API

```javascript
const { sendEmail } = require('@fourtwentydev/mailservice');

// Send a simple email
sendEmail('YOUR_API_KEY', {
  subject: 'Hello!',
  text: 'This is a test email',
})
  .then(response => console.log('Email sent:', response))
  .catch(error => console.error('Failed to send email:', error));
```

### Class-based API

```javascript
const { FTMailClient } = require('@fourtwentydev/mailservice');

// Create a client with custom options
const client = new FTMailClient('YOUR_API_KEY', {
  retry: {
    enabled: true,
    maxRetries: 5,
    strategy: 'exponential'
  },
  timeout: 15000 // 15 seconds
});

// Send an email with HTML content
client.sendEmail({
  subject: 'Hello with HTML!',
  text: 'This is a fallback plain text content',
  html: '<h1>Hello!</h1><p>This is an <b>HTML</b> email.</p>'
})
  .then(response => console.log('Email sent:', response))
  .catch(error => console.error('Failed to send email:', error));
```

## API Reference

### `sendEmail(apiKey, options, clientOptions?)`

Sends an email using the FourTwenty Email Service API.

#### Parameters

- `apiKey` (string): Your API key
- `options` (SendEmailOptions): Email options
  - `subject` (string): Email subject
  - `text` (string, optional): Plain text content
  - `html` (string, optional): HTML content (only available for paid plans)
  - `attachments` (Array, optional): Email attachments
- `clientOptions` (ClientOptions, optional): Client configuration options

#### Returns

- Promise<SendEmailResponse>: API response

### `FTMailClient`

A class for interacting with the FourTwenty Email Service API.

#### Constructor

```javascript
new FTMailClient(apiKey, options?)
```

- `apiKey` (string): Your API key
- `options` (ClientOptions, optional): Client configuration options
  - `baseUrl` (string, optional): Base URL for the API (default: 'https://mail.api.fourtwenty.dev')
  - `retry` (object, optional): Retry configuration
    - `enabled` (boolean): Whether to enable automatic retries (default: true)
    - `maxRetries` (number): Maximum number of retry attempts (default: 3)
    - `strategy` ('linear' | 'exponential'): Retry strategy (default: 'exponential')
    - `initialDelay` (number): Initial delay in milliseconds (default: 1000)
  - `timeout` (number, optional): Request timeout in milliseconds (default: 10000)

#### Methods

##### `sendEmail(options)`

Sends an email.

- `options` (SendEmailOptions): Email options
  - `subject` (string): Email subject
  - `text` (string, optional): Plain text content
  - `html` (string, optional): HTML content (only available for paid plans)
  - `attachments` (Array, optional): Email attachments
    - `filename` (string): Filename of the attachment
    - `content` (Buffer | string | ReadStream): Content of the attachment
    - `contentType` (string, optional): MIME type of the attachment

## Error Handling

The client provides detailed error types to help you handle different error scenarios:

```javascript
const { 
  FTMailError, 
  RateLimitError, 
  NetworkError, 
  AuthError, 
  ValidationError, 
  ServerError 
} = require('@fourtwentydev/mailservice');

client.sendEmail({
  subject: 'Test email',
  text: 'This is a test'
})
  .then(response => console.log('Email sent:', response))
  .catch(error => {
    if (error instanceof RateLimitError) {
      console.error('Rate limit exceeded. Try again later.');
    } else if (error instanceof NetworkError) {
      console.error('Network issue. Check your connection.');
    } else if (error instanceof AuthError) {
      console.error('Authentication failed. Check your API key.');
    } else if (error instanceof ValidationError) {
      console.error('Validation error:', error.message);
    } else if (error instanceof ServerError) {
      console.error('Server error. Try again later.');
    } else {
      console.error('Unknown error:', error);
    }
  });
```

## Examples

### Sending an Email with Attachments

```javascript
const fs = require('fs');
const { sendEmail } = require('@fourtwentydev/mailservice');

sendEmail('YOUR_API_KEY', {
  subject: 'Email with Attachments',
  text: 'Please find the attached files.',
  attachments: [
    {
      filename: 'document.pdf',
      content: fs.readFileSync('./document.pdf')
    },
    {
      filename: 'image.jpg',
      content: fs.readFileSync('./image.jpg')
    }
  ]
})
  .then(response => console.log('Email sent:', response))
  .catch(error => console.error('Failed to send email:', error));
```

### Using in a Browser Environment

```javascript
import { FTMailClient } from '@fourtwentydev/mailservice';

const client = new FTMailClient('YOUR_API_KEY');

// Handle file input change
document.getElementById('attachment').addEventListener('change', (event) => {
  const file = event.target.files[0];
  
  // Send email with attachment
  client.sendEmail({
    subject: 'Email from Browser',
    text: 'This email was sent from a browser with an attachment.',
    attachments: [
      {
        filename: file.name,
        content: file,
        contentType: file.type
      }
    ]
  })
    .then(response => {
      console.log('Email sent:', response);
      alert('Email sent successfully!');
    })
    .catch(error => {
      console.error('Failed to send email:', error);
      alert(`Failed to send email: ${error.message}`);
    });
});
```

## License

MIT