Send Emails
Learn how to send transactional emails, bulk campaigns, and automated sequences with the OMX Email SDK.
Email Sending
The OMX Email SDK provides powerful capabilities for sending transactional emails, bulk campaigns, and automated email sequences with advanced personalization, scheduling, and delivery optimization.
Quick Start
Send your first email with just a few lines of code:
import { OMXClient } from '@omx-sdk/email';
const omx = new OMXClient({
clientId: 'your_client_id',
secretKey: 'your_secret_key'
});
// Send a simple email
const result = await omx.email.send({
to: 'user@example.com',
subject: 'Welcome to Our App!',
text: 'Thanks for signing up. We're excited to have you on board.',
html: '<h1>Welcome!</h1><p>Thanks for signing up. We're excited to have you on board.</p>'
});
console.log('Email sent:', result.messageId);Transactional Emails
Send important transactional emails with guaranteed delivery:
// Welcome email after signup
const welcomeEmail = await omx.email.send({
to: 'user@example.com',
from: {
email: 'welcome@yourapp.com',
name: 'YourApp Team'
},
subject: 'Welcome to YourApp!',
template: 'welcome',
data: {
firstName: 'John',
activationLink: 'https://yourapp.com/activate/abc123',
supportEmail: 'support@yourapp.com'
},
// High priority for transactional emails
priority: 'high',
category: 'transactional'
});
// Password reset email
const resetEmail = await omx.email.send({
to: user.email,
subject: 'Reset Your Password',
template: 'password_reset',
data: {
firstName: user.firstName,
resetLink: `https://yourapp.com/reset/${resetToken}`,
expiresIn: '24 hours'
},
// Security settings for sensitive emails
tracking: {
opens: false,
clicks: false
},
priority: 'high'
});
// Order confirmation
const orderConfirmation = await omx.email.send({
to: order.customerEmail,
subject: `Order Confirmation #${order.number}`,
template: 'order_confirmation',
data: {
orderNumber: order.number,
items: order.items,
total: order.total,
estimatedDelivery: order.estimatedDelivery,
trackingUrl: order.trackingUrl
},
// Attach receipt
attachments: [
{
filename: `receipt_${order.number}.pdf`,
content: await generateReceiptPDF(order),
contentType: 'application/pdf'
}
]
});Bulk Email Campaigns
Send marketing campaigns to large recipient lists efficiently:
// Create a bulk campaign
const campaign = await omx.email.createCampaign({
name: 'Monthly Newsletter - January 2024',
subject: 'Your Monthly Update is Here!',
template: 'newsletter',
// Recipient list
recipients: [
{ email: 'user1@example.com', data: { firstName: 'John' } },
{ email: 'user2@example.com', data: { firstName: 'Jane' } }
],
// Or use a segment
segment: 'active_subscribers',
// Campaign settings
settings: {
sendRate: 1000, // emails per hour
timezone: 'America/New_York',
unsubscribeLink: true,
trackingPixel: true
},
// A/B testing
abTest: {
enabled: true,
testPercentage: 20,
variants: [
{
name: 'Version A',
subject: 'Your Monthly Update is Here!',
template: 'newsletter_a'
},
{
name: 'Version B',
subject: 'Don't Miss This Month's Updates!',
template: 'newsletter_b'
}
],
winnerCriteria: 'open_rate',
testDuration: '4h'
}
});
// Schedule the campaign
await omx.email.scheduleCampaign(campaign.id, {
sendAt: '2024-01-15T10:00:00Z',
timezone: 'America/New_York'
});
// Monitor campaign progress
const progress = await omx.email.getCampaignProgress(campaign.id);
console.log(progress);
// {
// sent: 1250,
// delivered: 1180,
// bounced: 45,
// opened: 472,
// clicked: 89,
// unsubscribed: 3
// }Email Personalization
Create highly personalized emails with dynamic content:
// Advanced personalization
const personalizedEmail = await omx.email.send({
to: 'user@example.com',
subject: 'Recommended for You, {{firstName}}!',
template: 'personalized_recommendations',
// User-specific data
data: {
firstName: 'John',
location: 'New York',
previousPurchases: [
{ name: 'Wireless Headphones', category: 'Electronics' },
{ name: 'Coffee Maker', category: 'Home & Kitchen' }
],
// Dynamic recommendations based on user behavior
recommendations: await getPersonalizedRecommendations(userId),
// Location-based content
localOffers: await getLocalOffers(user.location),
// Time-sensitive content
todaysDeals: await getTodaysDeals(),
// Social proof
friendsActivity: await getFriendsActivity(userId)
},
// Dynamic content blocks
contentBlocks: {
weatherUpdate: await getWeatherContent(user.location),
localEvents: await getLocalEvents(user.location, user.interests)
}
});
// Conditional content based on user segments
const segmentedEmail = await omx.email.send({
to: user.email,
template: 'promotional_offer',
data: {
firstName: user.firstName,
// Show different content based on user tier
offer: user.tier === 'premium' ? {
discount: '25%',
freeShipping: true,
earlyAccess: true
} : {
discount: '15%',
freeShipping: false,
earlyAccess: false
},
// Personalized product recommendations
products: await getRecommendedProducts(user.id, user.preferences)
}
});Automated Email Sequences
Set up automated email sequences and drip campaigns:
// Create an automated sequence
const sequence = await omx.email.createSequence({
name: 'Welcome Series',
trigger: 'user_signup',
emails: [
{
delay: 0, // Send immediately
template: 'welcome_email',
subject: 'Welcome to YourApp!'
},
{
delay: '1d', // 1 day later
template: 'getting_started',
subject: 'Get the most out of YourApp',
conditions: {
// Only send if user hasn't completed onboarding
userSegment: 'not_onboarded'
}
},
{
delay: '3d', // 3 days after signup
template: 'feature_highlight',
subject: 'Discover powerful features',
conditions: {
userActivity: 'low' // Only for users with low activity
}
},
{
delay: '7d', // 1 week later
template: 'success_stories',
subject: 'See how others are succeeding'
}
],
// Sequence settings
settings: {
timezone: 'user_timezone',
sendTime: '10:00', // 10 AM in user's timezone
pauseOnWeekends: false,
stopOnUnsubscribe: true
}
});
// Enroll user in sequence
await omx.email.enrollInSequence(userId, sequence.id, {
data: {
firstName: user.firstName,
signupDate: user.createdAt,
referralSource: user.referralSource
}
});
// Abandoned cart sequence
const abandonedCartSequence = await omx.email.createSequence({
name: 'Abandoned Cart Recovery',
trigger: 'cart_abandoned',
emails: [
{
delay: '1h',
template: 'cart_reminder',
subject: 'You left something in your cart'
},
{
delay: '24h',
template: 'cart_discount',
subject: 'Complete your purchase - 10% off',
conditions: {
cartValue: { min: 50 } // Only for carts over $50
}
},
{
delay: '72h',
template: 'last_chance',
subject: 'Last chance - your items are going fast!'
}
]
});Scheduled Emails
Schedule emails for optimal delivery times:
// Schedule an email for later
const scheduledEmail = await omx.email.schedule({
to: 'user@example.com',
subject: 'Your weekly report is ready',
template: 'weekly_report',
data: { reportData: await generateWeeklyReport(userId) },
// Schedule for next Monday at 9 AM
sendAt: '2024-01-22T09:00:00',
timezone: 'America/New_York'
});
// Schedule with optimal send time
const optimizedEmail = await omx.email.scheduleOptimal({
to: user.email,
subject: 'Special offer just for you',
template: 'promotional_offer',
// Let AI determine the best send time for this user
optimization: {
method: 'user_behavior', // or 'global_optimal'
fallbackTime: '10:00',
timezone: user.timezone
}
});
// Recurring scheduled emails
const recurringEmail = await omx.email.scheduleRecurring({
name: 'Weekly Newsletter',
template: 'newsletter',
recipients: 'newsletter_subscribers',
schedule: {
frequency: 'weekly',
dayOfWeek: 'monday',
time: '10:00',
timezone: 'America/New_York'
},
// Dynamic content generation
contentGenerator: async () => {
return {
weeklyHighlights: await getWeeklyHighlights(),
featuredArticles: await getFeaturedArticles(),
upcomingEvents: await getUpcomingEvents()
};
}
});
// Cancel or modify scheduled emails
await omx.email.cancelScheduled(scheduledEmail.id);
await omx.email.updateScheduled(scheduledEmail.id, {
sendAt: '2024-01-22T10:00:00'
});Email Attachments
Send emails with various types of attachments:
// Send email with file attachments
const emailWithAttachments = await omx.email.send({
to: 'customer@example.com',
subject: 'Your invoice and receipt',
template: 'invoice_email',
data: {
invoiceNumber: 'INV-2024-001',
customerName: 'John Doe'
},
attachments: [
{
filename: 'invoice.pdf',
content: await generateInvoicePDF(invoiceData),
contentType: 'application/pdf'
},
{
filename: 'receipt.pdf',
content: receiptBuffer,
contentType: 'application/pdf'
},
{
filename: 'terms.docx',
path: '/documents/terms_and_conditions.docx'
}
]
});
// Dynamic attachments based on user data
const reportEmail = await omx.email.send({
to: user.email,
subject: 'Your monthly analytics report',
template: 'analytics_report',
attachments: await generateReportAttachments(user.id, {
format: user.preferences.reportFormat, // 'pdf' or 'excel'
includeCharts: true,
period: 'last_month'
})
});
// Inline attachments (embedded images)
const emailWithInlineImages = await omx.email.send({
to: 'user@example.com',
subject: 'Product showcase',
html: `
<h1>Check out our new products!</h1>
<img src="cid:product1" alt="Product 1" />
<img src="cid:product2" alt="Product 2" />
`,
attachments: [
{
filename: 'product1.jpg',
content: fs.readFileSync('product1.jpg'),
contentType: 'image/jpeg',
cid: 'product1' // Content-ID for inline embedding
},
{
filename: 'product2.jpg',
content: fs.readFileSync('product2.jpg'),
contentType: 'image/jpeg',
cid: 'product2'
}
]
});Delivery Options and Settings
Configure advanced delivery options for different use cases:
// High-priority email with delivery confirmation
const urgentEmail = await omx.email.send({
to: 'admin@yourapp.com',
subject: 'URGENT: System Alert',
text: 'Critical system alert requires immediate attention.',
// Delivery options
priority: 'high',
deliveryConfirmation: true,
readReceipt: true,
// Retry settings for critical emails
retryPolicy: {
maxRetries: 5,
retryInterval: '30s',
backoffMultiplier: 2
}
});
// Bulk email with delivery optimization
const bulkEmail = await omx.email.sendBulk({
recipients: subscriberList,
subject: 'Monthly Newsletter',
template: 'newsletter',
// Delivery optimization
delivery: {
sendRate: 500, // emails per hour
batchSize: 100,
throttling: true,
// Reputation management
warmupMode: false,
respectSuppressionList: true,
// Time zone optimization
timezoneOptimization: true,
preferredSendTime: {
start: '09:00',
end: '17:00'
}
},
// Bounce and complaint handling
bounceHandling: {
hardBounceAction: 'suppress',
softBounceRetries: 3,
complaintAction: 'unsubscribe'
}
});
// Email with custom headers
const customEmail = await omx.email.send({
to: 'user@example.com',
subject: 'Custom tracking email',
template: 'notification',
// Custom headers for integration
headers: {
'X-Campaign-ID': 'summer_2024',
'X-User-Segment': 'premium',
'X-Priority': 'high',
'List-Unsubscribe': '<mailto:unsubscribe@yourapp.com>'
},
// Custom metadata for tracking
metadata: {
campaignId: 'summer_2024',
userSegment: 'premium',
source: 'automated_sequence'
}
});Error Handling and Monitoring
Implement robust error handling and monitoring for email delivery:
// Error handling with retry logic
try {
const result = await omx.email.send(emailData);
console.log('Email sent successfully:', result.messageId);
} catch (error) {
switch (error.code) {
case 'INVALID_EMAIL':
console.error('Invalid email address:', error.details);
break;
case 'RATE_LIMITED':
console.log('Rate limited, retrying in:', error.retryAfter);
setTimeout(() => omx.email.send(emailData), error.retryAfter * 1000);
break;
case 'TEMPLATE_NOT_FOUND':
console.error('Email template not found:', error.template);
break;
case 'QUOTA_EXCEEDED':
console.error('Monthly email quota exceeded');
break;
default:
console.error('Email sending failed:', error);
}
}
// Set up delivery monitoring
const monitor = omx.email.createMonitor({
events: ['delivered', 'bounced', 'complaint', 'opened', 'clicked'],
webhook: {
url: 'https://yourapp.com/email-webhooks',
secret: 'webhook_secret'
},
alerts: {
bounceRate: { threshold: 0.05, email: 'alerts@yourapp.com' },
complaintRate: { threshold: 0.01, email: 'alerts@yourapp.com' },
deliveryFailures: { threshold: 10, email: 'alerts@yourapp.com' }
}
});
// Real-time delivery status
const deliveryStatus = await omx.email.getDeliveryStatus(messageId);
console.log(deliveryStatus);
// {
// messageId: 'msg_123',
// status: 'delivered',
// timestamp: '2024-01-15T10:30:00Z',
// recipient: 'user@example.com',
// bounceReason: null,
// deliveryAttempts: 1
// }Best Practices
- Authentication: Set up SPF, DKIM, and DMARC records for better deliverability
- List Hygiene: Regularly clean your email lists and respect unsubscribes
- Content Quality: Avoid spam triggers and test your content
- Personalization: Use data to create relevant, personalized content
- Testing: A/B test subject lines, send times, and content
- Monitoring: Track delivery metrics and set up alerts for issues