@envloped/envloped-js
v1.1.0
Published
TypeScript/JavaScript SDK for Envloped email platform
Maintainers
Readme
@envloped/envloped-js
TypeScript/JavaScript SDK for Envloped - The AI-powered email platform for developers.
Features
- 🚀 Zero runtime dependencies - uses native Fetch API
- 📝 Full TypeScript support with comprehensive types
- 🎯 Client-side validation before API calls
- 🔄 Request cancellation with AbortController
- 🌐 Works in Node.js 18+ and all modern browsers
- 🛡️ Custom error classes with type guards
- ⚡ Builder pattern for fluent configuration
- 📦 ESM and CommonJS support
Installation
npm install @envloped/envloped-jsyarn add @envloped/envloped-jspnpm add @envloped/envloped-jsQuick Start
import { EnvlopedClient } from '@envloped/envloped-js';
const client = new EnvlopedClient({
apiKey: 'ev_test_api_key',
});
// Send an email
const response = await client.emails.send({
from: '[email protected]',
to: ['[email protected]'],
subject: 'Hello from Envloped',
html: '<h1>Hello World!</h1>',
});
console.log('Email sent:', response.messageId);Usage
Sending Emails
// Simple email
await client.emails.send({
from: '[email protected]',
to: ['[email protected]'],
subject: 'Test Email',
html: '<p>This is a test email.</p>',
});
// Multiple recipients
await client.emails.send({
from: '[email protected]',
to: [
'[email protected]',
{ email: '[email protected]', name: 'Jane Doe' },
],
cc: ['[email protected]'],
bcc: [{ email: '[email protected]', name: 'Hidden Recipient' }],
subject: 'Multiple Recipients',
html: '<p>Email with multiple recipients.</p>',
});
// Plain text email
await client.emails.send({
from: '[email protected]',
to: ['[email protected]'],
subject: 'Plain Text',
text: 'This is a plain text email.',
});
// Email with custom headers
await client.emails.send({
from: '[email protected]',
to: ['[email protected]'],
subject: 'Custom Headers',
html: '<p>Email with custom headers.</p>',
replyTo: '[email protected]',
headers: {
'X-Custom-Header': 'value',
'X-Priority': '1',
},
});Error Handling
import {
ValidationError,
UnauthorizedError,
RateLimitError,
isRateLimitError,
} from '@envloped/envloped-js';
try {
await client.emails.send({
from: '[email protected]',
to: ['[email protected]'],
subject: 'Test',
html: '<p>Test</p>',
});
} catch (error) {
if (error instanceof ValidationError) {
console.error('Validation failed:', error.message);
} else if (error instanceof UnauthorizedError) {
console.error('Invalid API key');
} else if (isRateLimitError(error)) {
console.error('Rate limit exceeded:', error.usage);
}
}Configuration
// Custom base URL and timeout
const client = new EnvlopedClient({
apiKey: 'ev_test_api_key',
baseURL: 'https://api.example.com',
timeout: 30000, // 30 seconds
});
// Builder pattern for fluent configuration
const client = new EnvlopedClient({ apiKey: 'ev_test_api_key' })
.withBaseURL('https://api.example.com')
.withTimeout(15000)
.withUserAgent('MyApp/1.0.0');Request Cancellation
const controller = new AbortController();
// Cancel after 100ms
setTimeout(() => controller.abort(), 100);
try {
await client.emails.send(
{
from: '[email protected]',
to: ['[email protected]'],
subject: 'Test',
html: '<p>Test</p>',
},
{
signal: controller.signal,
}
);
} catch (error) {
console.log('Request cancelled');
}Health Check
const response = await client.ping();
console.log('API Status:', response.message);
console.log('Company ID:', response.companyId);API Reference
EnvlopedClient
Main client for interacting with Envloped API.
Constructor
new EnvlopedClient(config: ClientConfig)Parameters:
apiKey(string, required) - Your Envloped API keybaseURL(string, optional) - Base URL for API requests (default:https://api.envloped.com)timeout(number, optional) - Request timeout in milliseconds (default:10000)fetch(function, optional) - Custom fetch implementationuserAgent(string, optional) - Custom user agent string
Methods
emails.send(params, config?)
Send an email.
Parameters:
params.from(string) - Sender email addressparams.to(array) - Recipient email addressesparams.subject(string) - Email subjectparams.html(string, optional) - HTML contentparams.text(string, optional) - Plain text contentparams.cc(array, optional) - CC recipientsparams.bcc(array, optional) - BCC recipientsparams.replyTo(string, optional) - Reply-to addressparams.headers(object, optional) - Custom headersconfig.signal(AbortSignal, optional) - Abort signal for cancellationconfig.timeout(number, optional) - Per-request timeout
Returns: Promise<SendEmailResponse>
ping(config?)
Check API health.
Returns: Promise<PingResponse>
Error Classes
EnvlopedError- Base error classValidationError(400) - Invalid request parametersUnauthorizedError(401) - Invalid or missing API keyForbiddenError(403) - Access deniedRateLimitError(429) - Rate limit exceededAPIError- Generic API errors (500, 502, etc.)EnvlopedNetworkError- Network failures
Type Guards
isValidationError(error)- Check for ValidationErrorisUnauthorizedError(error)- Check for UnauthorizedErrorisForbiddenError(error)- Check for ForbiddenErrorisRateLimitError(error)- Check for RateLimitErrorisAPIError(error)- Check for APIErrorisNetworkError(error)- Check for NetworkError
Browser Support
This SDK uses the native Fetch API, which is supported in:
- Chrome 42+
- Firefox 39+
- Safari 10.1+
- Edge 14+
- Node.js 18+
License
MIT
