@kirimemail/smtp-sdk
v1.0.1
Published
Node.js SDK for Kirim.Email SMTP API
Readme
@kirimemail/smtp-sdk
Node.js SDK for Kirim.Email SMTP API - A modern, fully-featured TypeScript SDK for managing SMTP credentials, domains, email sending, logs, and suppressions.
Features
- 🚀 Modern JavaScript/TypeScript with full type support
- 🔐 Simple Authentication - Basic Auth for all endpoints
- 📦 Lightweight - Only depends on
kyHTTP client - 🔄 Async/Await - Modern promise-based API
- 🛡️ Error Handling - Comprehensive exception classes
- 📖 Well Documented - Full JSDoc documentation
- 🧪 Tested - Built with testing in mind
- 📧 Complete API Coverage - All 5 API classes implemented
Installation
npm install @kirimemail/smtp-sdkQuick Start
Basic Authentication
The SDK uses Basic Authentication for all endpoints:
const { SmtpClient, CredentialsApi, DomainsApi } = require('@kirimemail/smtp-sdk');
// Initialize client with basic authentication
const client = new SmtpClient('your_username', 'your_token');
const credentialsApi = new CredentialsApi(client);
const domainsApi = new DomainsApi(client);
// List domains
const domains = await domainsApi.listDomains();
console.log(`Found ${domains.data.length} domains`);
// List credentials for a domain
const credentials = await credentialsApi.listCredentials('example.com');
console.log(`Found ${credentials.data.length} credentials`);TypeScript Usage
import {
SmtpClient,
CredentialsApi,
DomainsApi,
MessagesApi,
Credential,
Domain
} from '@kirimemail/smtp-sdk';
const client = new SmtpClient('username', 'token');
const credentialsApi = new CredentialsApi(client);
const domainsApi = new DomainsApi(client);
const messagesApi = new MessagesApi(client);
// Create a new credential
const credentialResult = await credentialsApi.createCredential('example.com', 'new_user');
if (credentialResult.success) {
const credential: Credential = credentialResult.data.credential;
console.log(`Created credential: ${credential.username}`);
console.log(`Password: ${credential.password}`); // Available only on create
}
// Send an email
const emailResult = await messagesApi.sendMessage('example.com', {
from: '[email protected]',
to: '[email protected]',
subject: 'Hello from Node.js SDK',
text: 'This is a test email sent using the KirimEmail Node.js SDK'
});API Reference
SmtpClient
The main HTTP client for the Kirim.Email SMTP API.
Constructor
new SmtpClient(username?, token?, baseUrl?)username?: string- Username for basic authenticationtoken?: string- Token for basic authenticationbaseUrl?: string- Base URL for the API (default:https://smtp-app.kirim.email)
Methods
get<T>(endpoint, params?, options?)- Make GET requestpost<T>(endpoint, data?, options?)- Make POST requestpostMultipart<T>(endpoint, data?, files?, options?)- Make POST request with multipart dataput<T>(endpoint, data?, options?)- Make PUT requestdelete<T>(endpoint, params?, options?)- Make DELETE requeststream<T>(endpoint, params?, options?)- Stream response data
API Classes
All API classes use Basic Authentication and follow the same pattern:
const client = new SmtpClient('username', 'token');
const api = new ApiClass(client);CredentialsApi
Manage SMTP credentials:
listCredentials(domain, params?)- List domain credentialscreateCredential(domain, username)- Create new credentialgetCredential(domain, credentialId)- Get credential detailsdeleteCredential(domain, credentialId)- Delete credentialresetPassword(domain, credentialId)- Reset credential password
DomainsApi
Manage domains and DNS settings:
listDomains(params?)- List all domainscreateDomain(options)- Create new domaingetDomain(domain)- Get domain detailsupdateDomain(domain, settings)- Update domain tracking settingsdeleteDomain(domain)- Delete domainsetupAuthDomain(domain, options)- Setup authentication domainverifyMandatoryRecords(domain)- Verify mandatory DNS recordsverifyAuthDomainRecords(domain)- Verify auth domain recordssetupTrackingDomain(domain, options)- Setup tracking domainverifyTrackingDomainRecords(domain)- Verify tracking domain records
MessagesApi
Send emails and manage messages:
sendMessage(domain, emailData)- Send simple emailsendMessageWithAttachments(domain, emailData, files)- Send email with attachmentssendBulkMessage(domain, emailData)- Send bulk emailsendTemplateMessage(domain, templateData)- Send template emailvalidateMessage(emailData)- Validate email datacreateFileUpload(filename, content, contentType?)- Create file upload object
LogsApi
Retrieve email logs and activity:
getLogs(domain, params?)- Get domain logs with filteringgetLogsByDateRange(domain, startDate, endDate, params?)- Get logs by date rangegetLogsByMessage(domain, messageGuid)- Get logs for specific messagestreamLogs(domain, params?)- Stream logs in real-time
SuppressionsApi
Manage email suppressions:
getSuppressions(domain, params?)- Get all suppressionsgetUnsubscribeSuppressions(domain, params?)- Get unsubscribe suppressionsgetBounceSuppressions(domain, params?)- Get bounce suppressionsgetWhitelistSuppressions(domain, params?)- Get whitelist suppressionscreateWhitelistSuppression(domain, recipient)- Add to whitelistdeleteUnsubscribeSuppressions(domain, ids)- Delete unsubscribe suppressionsdeleteBounceSuppressions(domain, ids)- Delete bounce suppressionsdeleteWhitelistSuppressions(domain, ids)- Delete whitelist suppressions
Models
Credential
Represents an SMTP credential with the following properties:
id?: number- Credential IDuserSmtpGuid?: string- User SMTP GUIDusername?: string- SMTP usernameisVerified?: boolean- Verification statusstatus?: boolean- Active statuspassword?: string- Password (available on create/reset)strengthInfo?: Record<string, any>- Password strength informationremoteSynced?: boolean- Remote sync status- And more timestamp fields...
Methods
getCreatedDate(): Date | null- Get created date as Date objectisActive(): boolean- Check if credential is activeisActiveAndVerified(): boolean- Check if active and verified
Pagination
Represents pagination metadata:
total?: number- Total number of itemsperPage?: number- Items per pagecurrentPage?: number- Current page numberlastPage?: number- Last page number
Methods
hasNextPage(): boolean- Check if more pages existhasPreviousPage(): boolean- Check if previous page existsgetNextPage(): number | null- Get next page numbergetSummary(): string- Get pagination summary
Error Handling
The SDK provides comprehensive error handling with custom exception classes:
try {
await credentialsApi.createCredential('example.com', 'test_user');
} catch (error) {
if (error.name === 'AuthenticationException') {
console.log('Authentication failed:', error.message);
} else if (error.name === 'ValidationException') {
console.log('Validation failed:', error.message);
if (error.hasErrors()) {
console.log('Field errors:', error.getErrorMessages());
}
} else if (error.name === 'NotFoundException') {
console.log('Resource not found:', error.message);
} else if (error.name === 'ServerException') {
console.log('Server error:', error.message);
} else {
console.log('API error:', error.message);
}
}Exception Classes
ApiException- Base exception for all API errorsAuthenticationException- Authentication errors (401, 403)ValidationException- Validation errors (400, 422)NotFoundException- Resource not found (404)ServerException- Server errors (500+)
Examples
See the examples/ directory for complete usage examples:
node examples/comprehensive-example.jsBasic Usage Examples
Working with Domains
const { DomainsApi } = require('@kirimemail/smtp-sdk');
const domainsApi = new DomainsApi(client);
// List all domains
const domains = await domainsApi.listDomains({ limit: 10 });
domains.data.forEach(domain => {
console.log(`Domain: ${domain.domain}, Verified: ${domain.isVerified}`);
});
// Create a new domain
const result = await domainsApi.createDomain({
domain: 'newdomain.com',
dkim_key_length: 2048
});
// Verify DNS records
const verification = await domainsApi.verifyMandatoryRecords('newdomain.com');
console.log('DKIM valid:', verification.data.records.dkim);Working with Credentials
const { CredentialsApi } = require('@kirimemail/smtp-sdk');
const credentialsApi = new CredentialsApi(client);
// Create a new SMTP credential
const credential = await credentialsApi.createCredential('example.com', 'newsletter');
console.log(`Username: ${credential.data.credential.username}`);
console.log(`Password: ${credential.data.password}`); // Save this securely
// List all credentials
const credentials = await credentialsApi.listCredentials('example.com');
console.log(`Found ${credentials.data.length} credentials`);
// Reset password
const resetResult = await credentialsApi.resetPassword('example.com', credentialId);
console.log(`New password: ${resetResult.data.new_password}`);Sending Emails
const { MessagesApi } = require('@kirimemail/smtp-sdk');
const messagesApi = new MessagesApi(client);
// Send a simple email
const result = await messagesApi.sendMessage('example.com', {
from: '[email protected]',
to: '[email protected]',
subject: 'Welcome!',
text: 'Thank you for joining us.',
html: '<h1>Thank you for joining us!</h1><p>Welcome to our service.</p>'
});
// Send email with attachment
const fs = require('fs');
const attachment = messagesApi.createFileUpload(
'document.pdf',
fs.readFileSync('document.pdf'),
'application/pdf'
);
await messagesApi.sendMessageWithAttachments('example.com', {
from: '[email protected]',
to: '[email protected]',
subject: 'Document attached',
text: 'Please find the document attached.'
}, [attachment]);
// Send bulk email
await messagesApi.sendBulkMessage('example.com', {
from: '[email protected]',
to: ['[email protected]', '[email protected]', '[email protected]'],
subject: 'Weekly Newsletter',
text: 'Here is your weekly newsletter...'
});Working with Logs
const { LogsApi } = require('@kirimemail/smtp-sdk');
const logsApi = new LogsApi(client);
// Get recent logs
const logs = await logsApi.getLogs('example.com', {
limit: 50,
start: '2024-01-01',
end: '2024-01-31'
});
logs.data.forEach(log => {
console.log(`${log.timestamp}: ${log.eventType} to ${log.recipient}`);
});
// Stream logs in real-time
for await (const log of logsApi.streamLogs('example.com', { limit: 100 })) {
console.log(`Live: ${log.eventType} - ${log.recipient}`);
}Managing Suppressions
const { SuppressionsApi } = require('@kirimemail/smtp-sdk');
const suppressionsApi = new SuppressionsApi(client);
// Get all suppressions
const suppressions = await suppressionsApi.getSuppressions('example.com');
console.log(`Total suppressions: ${suppressions.data.length}`);
// Get bounce suppressions
const bounces = await suppressionsApi.getBounceSuppressions('example.com');
// Add email to whitelist
await suppressionsApi.createWhitelistSuppression('example.com '[email protected]');
// Delete suppressions by IDs
await suppressionsApi.deleteBounceSuppressions('example.com', [1, 2, 3]);Development
Building
npm run buildTesting
npm testLinting
npm run lint
npm run lint:fixLicense
MIT License - see LICENSE file for details.
Support
- 📧 Email: [email protected]
- 🌐 Website: https://kirim.email
- 📚 Documentation: https://docs.kirim.email
- 🐛 Issues: https://github.com/kirimemail/kirimemail-smtp-node-sdk/issues
Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
Changelog
See CHANGELOG.md for version history and changes.
