npm package: @popovmp/postmark-email
Description: Postmark Email
Latest version: 1.1.1

# Postmark Email

A lightweight Node.js library for sending emails via [Postmark](https://postmarkapp.com) with TypeScript support, input validation, and automatic retry functionality.

## Features

- ✅ **TypeScript Support**: Full type definitions included
- ✅ **Input Validation**: Validates email addresses and required fields
- ✅ **Automatic Retries**: Configurable retry mechanism for network failures
- ✅ **Error Handling**: Comprehensive error reporting and logging
- ✅ **ESM Support**: Native ES modules
- ✅ **Lightweight**: Minimal dependencies

## Installation

```bash
npm install @popovmp/postmark-email
```

## Quick Start

```javascript
import { sendPostMarkEmail } from "@popovmp/postmark-email";

// Configure Postmark settings
const postmarkModel = {
    token: "YOUR-POSTMARK-SERVER-TOKEN",
    from: "support@example.com",
    url: "https://api.postmarkapp.com/email",
    retry: 60000, // Retry delay in milliseconds
};

// Compose your email
const mailModel = {
    to: "recipient@example.com",
    subject: "Welcome to our service!",
    message: "Thank you for signing up. We're excited to have you!",
    replyTo: "noreply@example.com", // Optional
    tag: "welcome", // Optional - for tracking
};

// Send the email
try {
    await sendPostMarkEmail(postmarkModel, mailModel);
    console.log("Email sent successfully!");
} catch (error) {
    console.error("Failed to send email:", error.message);
}
```

## API Reference

### `sendPostMarkEmail(postmarkModel, mailModel, retryCount?, maxRetries?)`

Sends an email via Postmark with automatic retry functionality.

#### Parameters

##### `postmarkModel: PostmarkModel`

Configuration object for Postmark service:

| Property | Type     | Required | Description |
|----------|----------|----------|-------------|
| `token`  | `string` | ✅       | Your Postmark server token |
| `from`   | `string` | ✅       | Sender email address |
| `url`    | `string` | ✅       | Postmark API endpoint (usually `https://api.postmarkapp.com/email`) |
| `retry`  | `number` | ✅       | Retry delay in milliseconds for failed requests |

##### `mailModel: MailModel`

Email content and recipient information:

| Property  | Type     | Required | Description |
|-----------|----------|----------|-------------|
| `to`      | `string` | ✅       | Recipient email address (validated) |
| `subject` | `string` | ✅       | Email subject line |
| `message` | `string` | ✅       | Email body (plain text) |
| `replyTo` | `string` | ❌       | Reply-to email address (validated if provided) |
| `tag`     | `string` | ❌       | Tag for email tracking and organization |

##### `retryCount?: number`

Current retry attempt (default: 0). Used internally for retry mechanism.

##### `maxRetries?: number`

Maximum number of retry attempts (default: 3).

#### Returns

`Promise<void>` - Resolves on successful email sending, rejects on failure.

#### Throws

- `Error` - On validation failures, network errors, or Postmark API errors

## Error Handling

The library provides comprehensive error handling for common scenarios:

```javascript
try {
    await sendPostMarkEmail(postmarkModel, mailModel);
} catch (error) {
    if (error.message.includes("Validation error")) {
        // Handle input validation errors
        console.error("Invalid input:", error.message);
    } else if (error.message.includes("Network error")) {
        // Handle network connectivity issues
        console.error("Network problem:", error.message);
    } else if (error.message.includes("Postmark Error")) {
        // Handle Postmark API errors
        console.error("Postmark API issue:", error.message);
    } else {
        // Handle other errors
        console.error("Unexpected error:", error.message);
    }
}
```

## Validation

The library automatically validates:

- **Email addresses**: Both `to` and `replyTo` fields must be valid email formats
- **Required fields**: All mandatory fields must be present and non-empty strings
- **Data types**: Ensures correct types for all parameters

## Retry Mechanism

The library includes automatic retry functionality:

- **Network failures** (status code 0) trigger automatic retries
- **Configurable delay**: Set via `postmarkModel.retry` (in milliseconds)
- **Maximum attempts**: Defaults to 3, configurable via `maxRetries` parameter
- **Exponential backoff**: Not implemented (uses fixed delay)

## TypeScript Support

Full TypeScript definitions are included:

```typescript
interface PostmarkModel {
    token: string;
    from: string;
    url: string;
    retry: number;
}

interface MailModel {
    to: string;
    subject: string;
    message: string;
    replyTo?: string;
    tag?: string;
}
```

## Examples

### Basic Email

```javascript
const postmarkModel = {
    token: "your-postmark-token",
    from: "noreply@yourcompany.com",
    url: "https://api.postmarkapp.com/email",
    retry: 30000,
};

const mailModel = {
    to: "customer@example.com",
    subject: "Order Confirmation",
    message: "Your order #12345 has been confirmed and will ship soon.",
};

await sendPostMarkEmail(postmarkModel, mailModel);
```

### Email with Tags and Reply-To

```javascript
const mailModel = {
    to: "user@example.com",
    subject: "Password Reset",
    message: "Click the link below to reset your password...",
    replyTo: "support@yourcompany.com",
    tag: "password-reset",
};

await sendPostMarkEmail(postmarkModel, mailModel);
```

### Custom Retry Configuration

```javascript
// Send with custom retry settings
await sendPostMarkEmail(
    postmarkModel, 
    mailModel, 
    0,  // Starting retry count
    5   // Maximum 5 retry attempts
);
```

## Dependencies

- [`@popovmp/client-request`](https://www.npmjs.com/package/@popovmp/client-request) - HTTP client for API requests
- [`@popovmp/logger`](https://www.npmjs.com/package/@popovmp/logger) - Logging functionality

## Development

```bash
# Run tests
npm test

# Run linting
npm run lint

# Type checking
npm run check
```

## License

MIT

## Contributing

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## Changelog

### v1.0.0

- Initial release
- TypeScript support
- Input validation
- Automatic retry mechanism
- Comprehensive error handling