@fredabod/harp-email-sdk
v1.0.0
Published
Official Harp Email SDK for sending emails via the Harp Email API
Maintainers
Readme
@fredabod/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
npm install @fredabod/harp-email-sdkQuick Start
import { HarpEmailClient } from '@fredabod/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: '[email protected]',
to: ['[email protected]'],
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
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:
export HARP_API_KEY="your-api-key-here"const client = new HarpEmailClient({
apiKey: process.env.HARP_API_KEY!
});API Reference
Sending Emails
Send Single Email
const emailData = {
from: '[email protected]',
to: ['[email protected]'],
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
const bulkData = {
emails: [
{
from: '[email protected]',
to: ['[email protected]'],
subject: 'Welcome User 1',
htmlContent: '<h1>Welcome!</h1>'
},
{
from: '[email protected]',
to: ['[email protected]'],
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
const templateData = {
templateId: 'template-123',
from: '[email protected]',
to: ['[email protected]'],
variables: {
userName: 'John Doe',
activationLink: 'https://example.com/activate/123'
}
};
const response = await client.sendTemplateEmail(templateData);Template Management
Get All Templates
const templates = await client.getTemplates();
console.log('Available templates:', templates);Get Specific Template
const template = await client.getTemplate('template-123');
console.log('Template details:', template);Create Template
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
const updatedTemplate = await client.updateTemplate('template-123', {
subject: 'Updated Welcome {{userName}}!',
htmlContent: '<h1>Updated Welcome {{userName}}!</h1>'
});Delete Template
await client.deleteTemplate('template-123');Analytics and Tracking
Get API Key Information
const apiInfo = await client.getApiKeyInfo();
console.log('Usage stats:', apiInfo.usage);
console.log('Quota limits:', apiInfo.quotaLimits);Get Email Statistics
// 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
const trackingInfo = await client.trackEmail('tracking-id-123');
console.log('Email status:', trackingInfo.status);
console.log('Delivery events:', trackingInfo.events);Verify Email Address
const verification = await client.verifyEmail('[email protected]');
console.log('Is valid:', verification.valid);
console.log('Is deliverable:', verification.deliverable);Advanced Usage
Error Handling
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)
const client = new HarpEmailClient({
apiKey: 'your-api-key',
baseURL: 'https://your-domain.com/api' // Your self-hosted instance
});Timeout Configuration
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:
import {
HarpEmailClient,
EmailData,
EmailResponse,
EmailTemplate,
BulkEmailResponse
} from '@fredabod/harp-email-sdk';
// All types are fully typed and provide IntelliSense
const emailData: EmailData = {
from: '[email protected]',
to: ['[email protected]'],
subject: 'Typed Email',
htmlContent: '<p>Fully typed!</p>'
};Examples
Newsletter Subscription
import { HarpEmailClient } from '@fredabod/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: '[email protected]',
to: [userEmail],
variables: {
userName,
unsubscribeLink: `https://yoursite.com/unsubscribe?email=${userEmail}`
}
});
}Order Confirmation
async function sendOrderConfirmation(order: Order) {
return await client.sendEmail({
from: '[email protected]',
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
async function sendCampaign(subscribers: Subscriber[], campaignContent: string) {
const emails = subscribers.map(subscriber => ({
from: '[email protected]',
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:
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
- API Reference: https://api.harp.email/docs
- GitHub Issues: https://github.com/harp-tech/email-sdk/issues
- Email Support: [email protected]
License
MIT License - see LICENSE file for details.
