npm package: @pappymall/mail
Description: Official Node.js SDK for PappyMail - Send transactional emails, manage campaigns, and build email experiences.
Author: PappyMall
Latest version: 1.0.2

# PappyMail SDK for Node.js

Official Node.js SDK for [PappyMail](https://pappymall.com) - A powerful email platform combining transactional email, campaigns, and inbox capabilities.

## Installation

```bash
npm install @pappymall/mail
# or
yarn add @pappymall/mail
# or
pnpm add @pappymall/mail
```

## Quick Start

```typescript
import { PappyMail } from '@pappymall/mail';

const client = new PappyMail('pm_live_your_api_key');

// Send a simple email
const response = await client.sendSimple({
  from: 'noreply@yourdomain.com',
  to: 'user@example.com',
  subject: 'Hello from PappyMail!',
  html: '<h1>Welcome!</h1><p>Thanks for signing up.</p>',
});

console.log(`Message ID: ${response.message_id}`);
```

## Features

### Send Transactional Emails

```typescript
const response = await client.mail.send({
  from: { email: 'noreply@yourdomain.com', name: 'Your App' },
  to: [{ email: 'user@example.com', name: 'John Doe' }],
  subject: 'Order Confirmation',
  html_content: '<h1>Order #12345</h1><p>Thank you for your order!</p>',
  text_content: 'Order #12345 - Thank you for your order!',
});

console.log(`Message ID: ${response.message_id}`);
```

### Send Batch Emails

```typescript
const response = await client.mail.sendBatch([
  {
    from: { email: 'noreply@yourdomain.com' },
    to: [{ email: 'alice@example.com' }],
    subject: 'Hello Alice!',
    html_content: '<p>Welcome Alice!</p>',
  },
  {
    from: { email: 'noreply@yourdomain.com' },
    to: [{ email: 'bob@example.com' }],
    subject: 'Hello Bob!',
    html_content: '<p>Welcome Bob!</p>',
  },
]);

console.log(`Sent: ${response.successful} of ${response.total}`);
```

### Get Email Status

```typescript
const status = await client.mail.getStatus('msg_abc123xyz');
console.log(`Status: ${status.status}`);
```

### Manage Email Templates

```typescript
// Create template
const template = await client.templates.create({
  name: 'Welcome Email',
  html_content: '<h1>Welcome!</h1><p>Thanks for joining us.</p>',
});

// List templates
const templates = await client.templates.list();
console.log(`Found ${templates.pagination.total} templates`);

// Get template
const detail = await client.templates.get(template.id);

// Update template
await client.templates.update(template.id, {
  name: 'Updated Welcome',
  html_content: '<h1>Welcome!</h1><p>We are excited to have you!</p>',
});

// Delete template
await client.templates.delete(template.id);
```


### Domain Management

```typescript
// Add domain
const domain = await client.domains.add('yourdomain.com');

// Get DNS records to configure
domain.dns_records?.forEach((record) => {
  console.log(`${record.type}: ${record.name} -> ${record.value}`);
});

// Verify domain
const verification = await client.domains.verify(domain.id);
if (verification.is_verified) {
  console.log('Domain verified successfully!');
}
```

### Webhooks

```typescript
// Create webhook
const webhook = await client.webhooks.create(
  'https://yourapp.com/webhooks/email',
  ['delivered', 'opened', 'clicked', 'bounced']
);

// List webhooks
const webhooks = await client.webhooks.list();

// Delete webhook
await client.webhooks.delete(webhook.id);

// Verify webhook signature in your endpoint (Express example)
app.post('/webhooks/email', (req, res) => {
  const payload = JSON.stringify(req.body);
  const signature = req.headers['x-pappymail-signature'] as string;

  if (!PappyMail.verifyWebhookSignature(payload, signature, 'your_webhook_secret')) {
    return res.status(401).send('Invalid signature');
  }

  // Process webhook...
  res.sendStatus(200);
});
```

### Analytics

```typescript
// Get global account stats
const global = await client.stats.getGlobal();
console.log(`Daily usage: ${global.daily_usage}/${global.daily_limit}`);
console.log(`Monthly usage: ${global.monthly_usage}/${global.monthly_limit}`);
```

## Configuration

### Full Options

```typescript
const client = new PappyMail({
  apiKey: 'pm_live_your_api_key',
  baseUrl: 'https://pappymall.com/api/v1', // default
  timeout: 30000, // 30 seconds
  maxRetries: 3, // default
  enableRetry: true, // default
});
```


## Error Handling

```typescript
import {
  PappyMailError,
  ValidationError,
  RateLimitError,
  UnauthorizedError,
} from '@pappymall/mail';

try {
  const response = await client.mail.send(request);
} catch (error) {
  if (error instanceof ValidationError) {
    console.log(`Validation error: ${error.message}`);
    error.details?.forEach((detail) => {
      console.log(`  - ${detail.field}: ${detail.message}`);
    });
  } else if (error instanceof RateLimitError) {
    console.log(`Rate limited. Retry after: ${error.retryAfter} seconds`);
  } else if (error instanceof UnauthorizedError) {
    console.log('Invalid API key');
  } else if (error instanceof PappyMailError) {
    console.log(`Error: ${error.code} - ${error.message}`);
  }
}
```

## TypeScript Support

This SDK is written in TypeScript and provides full type definitions out of the box.

```typescript
import type {
  SendEmailRequest,
  SendEmailResponse,
  Campaign,
  Contact,
} from '@pappymall/mail';

const request: SendEmailRequest = {
  from: { email: 'noreply@yourdomain.com' },
  to: [{ email: 'user@example.com' }],
  subject: 'Hello!',
  html_content: '<p>Hello World</p>',
};
```

## Requirements

- Node.js 16+
- Node.js 18+ (for native fetch) or `node-fetch` package

## License

MIT License - see LICENSE file for details.

## Support

- Documentation: https://pappymall.com/Public/MailApi
- Contact: https://pappymall.com/Public/Contact
- Email: support@pappymall.com