npm package: @harp-messaging/harp-email-sdk
Description: Official Harp Email SDK for sending emails via the Harp Email API
Author: Harp Team
Latest version: 1.0.0

# @harp-messaging/harp-email-sdk

A TypeScript SDK for the Harp Email API that provides a simple and intuitive interface for sending emails, managing templates, and tracking email delivery.

## Installation

```bash
npm install @harp-messaging/harp-email-sdk
```

## Quick Start

```typescript
import { HarpEmailClient } from '@harp-messaging/harp-email-sdk';

const client = new HarpEmailClient({
  apiKey: 'your-api-key-here',
  baseURL: 'https://api.harp.email' // Optional, defaults to production
});

// Send a simple email
const result = await client.sendEmail({
  from: 'sender@example.com',
  to: ['recipient@example.com'],
  subject: 'Hello from Harp!',
  htmlContent: '<h1>Welcome to Harp Email!</h1>',
  textContent: 'Welcome to Harp Email!'
});

console.log('Email sent:', result.id);
```

## Configuration

### Constructor Options

```typescript
interface HarpEmailConfig {
  apiKey: string;        // Your Harp API key (required)
  baseURL?: string;      // API base URL (optional, defaults to production)
  timeout?: number;      // Request timeout in ms (optional, default: 30000)
  retries?: number;      // Number of retries for failed requests (optional, default: 3)
}
```

### Environment Variables

You can also set your API key using environment variables:

```bash
export HARP_API_KEY="your-api-key-here"
```

```typescript
const client = new HarpEmailClient({
  apiKey: process.env.HARP_API_KEY!
});
```

## API Reference

### Sending Emails

#### Send Single Email

```typescript
const emailData = {
  from: 'sender@example.com',
  to: ['recipient@example.com'],
  subject: 'Test Email',
  htmlContent: '<p>Hello World!</p>',
  textContent: 'Hello World!',
  attachments: [
    {
      filename: 'document.pdf',
      content: 'base64-encoded-content',
      contentType: 'application/pdf'
    }
  ]
};

const response = await client.sendEmail(emailData);
```

#### Send Bulk Emails

```typescript
const bulkData = {
  emails: [
    {
      from: 'sender@example.com',
      to: ['user1@example.com'],
      subject: 'Welcome User 1',
      htmlContent: '<h1>Welcome!</h1>'
    },
    {
      from: 'sender@example.com',
      to: ['user2@example.com'],
      subject: 'Welcome User 2',
      htmlContent: '<h1>Welcome!</h1>'
    }
  ]
};

const response = await client.sendBulkEmails(bulkData);
console.log(`Sent ${response.successful} emails, ${response.failed} failed`);
```

#### Send Template Email

```typescript
const templateData = {
  templateId: 'template-123',
  from: 'sender@example.com',
  to: ['recipient@example.com'],
  variables: {
    userName: 'John Doe',
    activationLink: 'https://example.com/activate/123'
  }
};

const response = await client.sendTemplateEmail(templateData);
```

### Template Management

#### Get All Templates

```typescript
const templates = await client.getTemplates();
console.log('Available templates:', templates);
```

#### Get Specific Template

```typescript
const template = await client.getTemplate('template-123');
console.log('Template details:', template);
```

#### Create Template

```typescript
const newTemplate = await client.createTemplate({
  name: 'Welcome Email',
  subject: 'Welcome {{userName}}!',
  htmlContent: '<h1>Welcome {{userName}}!</h1><p>Click {{activationLink}} to activate.</p>',
  textContent: 'Welcome {{userName}}! Click {{activationLink}} to activate.',
  variables: ['userName', 'activationLink']
});
```

#### Update Template

```typescript
const updatedTemplate = await client.updateTemplate('template-123', {
  subject: 'Updated Welcome {{userName}}!',
  htmlContent: '<h1>Updated Welcome {{userName}}!</h1>'
});
```

#### Delete Template

```typescript
await client.deleteTemplate('template-123');
```

### Analytics and Tracking

#### Get API Key Information

```typescript
const apiInfo = await client.getApiKeyInfo();
console.log('Usage stats:', apiInfo.usage);
console.log('Quota limits:', apiInfo.quotaLimits);
```

#### Get Email Statistics

```typescript
// Get today's stats
const todayStats = await client.getEmailStats('today');

// Get weekly stats
const weeklyStats = await client.getEmailStats('week');

// Get monthly stats
const monthlyStats = await client.getEmailStats('month');
```

#### Track Email Delivery

```typescript
const trackingInfo = await client.trackEmail('tracking-id-123');
console.log('Email status:', trackingInfo.status);
console.log('Delivery events:', trackingInfo.events);
```

#### Verify Email Address

```typescript
const verification = await client.verifyEmail('test@example.com');
console.log('Is valid:', verification.valid);
console.log('Is deliverable:', verification.deliverable);
```

## Advanced Usage

### Error Handling

```typescript
try {
  const result = await client.sendEmail(emailData);
  console.log('Success:', result);
} catch (error) {
  if (error.message.includes('Rate limit exceeded')) {
    console.log('Rate limited, waiting...');
    await new Promise(resolve => setTimeout(resolve, 60000));
    // Retry logic here
  } else if (error.message.includes('Invalid API key')) {
    console.error('Authentication failed');
  } else {
    console.error('Email failed:', error.message);
  }
}
```

### Custom Base URL (Self-hosted)

```typescript
const client = new HarpEmailClient({
  apiKey: 'your-api-key',
  baseURL: 'https://your-domain.com/api' // Your self-hosted instance
});
```

### Timeout Configuration

```typescript
const client = new HarpEmailClient({
  apiKey: 'your-api-key',
  timeout: 60000, // 60 seconds
  retries: 5      // Retry failed requests 5 times
});
```

## TypeScript Support

This SDK is built with TypeScript and provides full type definitions:

```typescript
import { 
  HarpEmailClient, 
  EmailData, 
  EmailResponse, 
  EmailTemplate,
  BulkEmailResponse 
} from '@harp-messaging/harp-email-sdk';

// All types are fully typed and provide IntelliSense
const emailData: EmailData = {
  from: 'sender@example.com',
  to: ['recipient@example.com'],
  subject: 'Typed Email',
  htmlContent: '<p>Fully typed!</p>'
};
```

## Examples

### Newsletter Subscription

```typescript
import { HarpEmailClient } from '@harp-messaging/harp-email-sdk';

const client = new HarpEmailClient({
  apiKey: process.env.HARP_API_KEY!
});

async function sendWelcomeEmail(userEmail: string, userName: string) {
  return await client.sendTemplateEmail({
    templateId: 'welcome-newsletter',
    from: 'newsletter@yourcompany.com',
    to: [userEmail],
    variables: {
      userName,
      unsubscribeLink: `https://yoursite.com/unsubscribe?email=${userEmail}`
    }
  });
}
```

### Order Confirmation

```typescript
async function sendOrderConfirmation(order: Order) {
  return await client.sendEmail({
    from: 'orders@yourstore.com',
    to: [order.customerEmail],
    subject: `Order Confirmation #${order.id}`,
    htmlContent: `
      <h1>Order Confirmed!</h1>
      <p>Your order #${order.id} has been confirmed.</p>
      <p>Total: $${order.total}</p>
    `,
    attachments: [{
      filename: `invoice-${order.id}.pdf`,
      content: order.invoicePdf, // Base64 encoded PDF
      contentType: 'application/pdf'
    }]
  });
}
```

### Bulk Email Campaign

```typescript
async function sendCampaign(subscribers: Subscriber[], campaignContent: string) {
  const emails = subscribers.map(subscriber => ({
    from: 'campaigns@yourcompany.com',
    to: [subscriber.email],
    subject: 'Special Offer Just for You!',
    htmlContent: campaignContent.replace('{{name}}', subscriber.name),
    metadata: {
      campaignId: 'summer-sale-2024',
      subscriberId: subscriber.id
    }
  }));

  return await client.sendBulkEmails({ emails });
}
```

## Rate Limiting

The SDK automatically handles rate limiting and will throw descriptive errors when limits are exceeded. Implement retry logic with exponential backoff:

```typescript
async function sendEmailWithRetry(emailData: EmailData, maxRetries = 3) {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      return await client.sendEmail(emailData);
    } catch (error) {
      if (error.message.includes('Rate limit') && attempt < maxRetries) {
        const delay = Math.pow(2, attempt) * 1000; // Exponential backoff
        await new Promise(resolve => setTimeout(resolve, delay));
        continue;
      }
      throw error;
    }
  }
}
```

## Support

- **Documentation**: [https://docs.harp.email](https://docs.harp.email)
- **API Reference**: [https://api.harp.email/docs](https://api.harp.email/docs)
- **GitHub Issues**: [https://github.com/harp-tech/email-sdk/issues](https://github.com/harp-tech/email-sdk/issues)
- **Email Support**: support@harp.email

## License

MIT License - see LICENSE file for details.