Node.js SDK - Batch Operations
The mailiam Node.js SDK provides efficient batch sending for when you need to send multiple emails.
Basic Batch Sending
Section titled “Basic Batch Sending”Send multiple emails in one operation:
import { mailiam } from '@mailiam/node';
const mailiam = new mailiam({ apiKey: process.env.MAILIAM_API_KEY});
const result = await mailiam.emails.sendBatch([ { from: 'hello@mycompany.com', to: 'user1@example.com', subject: 'Welcome!', html: '<h1>Welcome user 1!</h1>' }, { from: 'hello@mycompany.com', to: 'user2@example.com', subject: 'Welcome!', html: '<h1>Welcome user 2!</h1>' }, { from: 'hello@mycompany.com', to: 'user3@example.com', subject: 'Welcome!', html: '<h1>Welcome user 3!</h1>' }]);
console.log(`Sent: ${result.sent}, Failed: ${result.failed}`);Batch Response
Section titled “Batch Response”The batch response includes detailed results:
const result = await mailiam.emails.sendBatch([...]);
console.log(result.total); // Total number of emailsconsole.log(result.sent); // Successfully sent countconsole.log(result.failed); // Failed count
// Individual resultsresult.results.forEach((item) => { if (item.success) { console.log(`Email ${item.index}: Sent (${item.messageId})`); } else { console.log(`Email ${item.index}: Failed (${item.error})`); }});Personalized Batch Emails
Section titled “Personalized Batch Emails”Send personalized emails to multiple users:
const users = [ { email: 'alice@example.com', name: 'Alice', points: 150 }, { email: 'bob@example.com', name: 'Bob', points: 200 }, { email: 'charlie@example.com', name: 'Charlie', points: 100 }];
const emails = users.map(user => ({ from: 'rewards@myapp.com', to: user.email, subject: `You have ${user.points} points!`, html: ` <h1>Hi ${user.name}!</h1> <p>You currently have <strong>${user.points}</strong> reward points.</p> <a href="https://myapp.com/rewards">View Rewards</a> `, text: `Hi ${user.name}! You have ${user.points} reward points. View rewards: https://myapp.com/rewards`}));
const result = await mailiam.emails.sendBatch(emails);Error Handling
Section titled “Error Handling”Each email in the batch has individual retry logic:
const result = await mailiam.emails.sendBatch([...]);
// Check for failuresif (result.failed > 0) { console.log(`${result.failed} emails failed:`);
result.results.forEach((item, index) => { if (!item.success) { console.log(`- Email to ${emails[index].to}: ${item.error}`); } });}Use Cases
Section titled “Use Cases”Daily Digest Emails
Section titled “Daily Digest Emails”async function sendDailyDigests(subscribers: User[]) { const emails = subscribers.map(user => ({ from: 'digest@myapp.com', to: user.email, subject: 'Your Daily Digest', html: generateDigestHTML(user), text: generateDigestText(user) }));
const result = await mailiam.emails.sendBatch(emails);
console.log(`Daily digest: ${result.sent} sent, ${result.failed} failed`);
return result;}Notification Blast
Section titled “Notification Blast”async function notifyAllUsers(announcement: string) { const users = await getAllUsers();
const emails = users.map(user => ({ from: 'announcements@myapp.com', to: user.email, subject: 'Important Announcement', html: `<h2>Announcement</h2><p>${announcement}</p>`, text: `Announcement\n\n${announcement}` }));
return await mailiam.emails.sendBatch(emails);}Password Reset Reminders
Section titled “Password Reset Reminders”async function sendPasswordResetReminders(users: User[]) { const emails = users.map(user => ({ from: 'security@myapp.com', to: user.email, subject: 'Complete Your Password Reset', html: ` <p>Hi ${user.name},</p> <p>You started a password reset but didn't complete it.</p> <a href="${generateResetLink(user)}">Complete Reset</a> ` }));
return await mailiam.emails.sendBatch(emails);}Best Practices
Section titled “Best Practices”Chunk Large Batches
Section titled “Chunk Large Batches”For very large batches, send in chunks:
async function sendLargeBatch(emails: SendEmailRequest[]) { const chunkSize = 100; const results = [];
for (let i = 0; i < emails.length; i += chunkSize) { const chunk = emails.slice(i, i + chunkSize); const result = await mailiam.emails.sendBatch(chunk); results.push(result);
console.log(`Chunk ${i / chunkSize + 1}: ${result.sent} sent`); }
return results;}Handle Partial Failures
Section titled “Handle Partial Failures”const result = await mailiam.emails.sendBatch(emails);
if (result.failed > 0) { // Log failures for investigation const failures = result.results.filter(r => !r.success); await logFailures(failures);
// Optionally retry failures const failedEmails = failures.map(f => emails[f.index]); // Implement retry logic}Rate Limit Awareness
Section titled “Rate Limit Awareness”The SDK handles rate limiting automatically, but for large batches, be aware of your rate limits:
- Usage keys: 1000 requests/hour
- Admin keys: 10000 requests/hour
Performance
Section titled “Performance”The batch operation:
- Sends emails sequentially with individual retry logic
- Each email gets automatic retry with exponential backoff
- Continues processing even if some emails fail
- Returns comprehensive results for all emails
Next Steps
Section titled “Next Steps”- Error Handling - Handle errors gracefully
- API Reference - Complete API documentation
- Examples - See batch sending in action