Send emails to contacts, tags, or direct email addresses using templates or raw HTML content.
Send Email
The SDK supports multiple recipient types and both template-based and raw HTML emails.
Send to Direct Email
Send to a specific email address without creating a contact:
const result = await sendmator.email.send({
recipient_type: 'direct_email',
direct_email: 'user@example.com',
template_key: 'welcome-email',
variables: {
name: 'John Doe',
loginUrl: 'https://app.example.com/login',
supportEmail: 'support@example.com'
}
});
console.log('Email sent:', result.success);
Send to Contact
Send to an existing contact using their external_id:
await sendmator.email.send({
recipient_type: 'contact',
contact_external_id: 'CRM-12345',
template_key: 'order-confirmation',
variables: {
orderNumber: '#12345',
total: '$99.99',
trackingUrl: 'https://tracking.example.com/12345'
}
});
Send to Tag
Send to all contacts with specific tags:
await sendmator.email.send({
recipient_type: 'tag',
tag: ['customer', 'newsletter'],
template_key: 'monthly-newsletter',
variables: {
month: 'January',
year: '2024'
}
});
Send to All Contacts
Send to your entire contact list:
await sendmator.email.send({
recipient_type: 'all',
template_key: 'important-announcement',
variables: {
announcementTitle: 'New Feature Launch',
announcementBody: 'We are excited to announce...'
}
});
Send Without Template
Send emails with raw HTML content instead of using a template:
await sendmator.email.send({
recipient_type: 'direct_email',
direct_email: 'user@example.com',
subject: 'Welcome to Acme App',
content: '<h1>Welcome!</h1><p>Thank you for signing up.</p>',
plain_text_content: 'Welcome! Thank you for signing up.',
from: 'hello@acme.com',
from_name: 'Acme Team',
reply_to: 'support@acme.com'
});
Complete Request Options
await sendmator.email.send({
// Recipient selection (required)
recipient_type: 'direct_email', // 'direct_email' | 'contact' | 'tag' | 'all'
direct_email: 'user@example.com', // For direct_email type
contact_external_id: 'CRM-123', // For contact type
tag: ['customer', 'vip'], // For tag type
// Template method
template_key: 'welcome-email', // Template identifier
variables: { // Template variables
name: 'John',
loginUrl: 'https://app.example.com'
},
// OR Raw content method
subject: 'Welcome!', // Email subject
content: '<h1>Hello</h1>', // HTML content
plain_text_content: 'Hello', // Plain text fallback
// Optional overrides
from: 'hello@acme.com', // Override sender email
from_name: 'Acme Team', // Override sender name
reply_to: 'support@acme.com', // Reply-to address
// Additional options
metadata: { // Custom tracking data
campaign: 'onboarding',
source: 'web'
},
triggerAt: '2024-02-01T10:00:00Z' // Schedule for future (ISO 8601 UTC)
});
Scheduled Emails
Schedule emails for future delivery:
const futureDate = new Date('2024-02-01T10:00:00Z');
await sendmator.email.send({
recipient_type: 'tag',
tag: ['newsletter'],
template_key: 'weekly-digest',
triggerAt: futureDate.toISOString(),
variables: {
week: 'Week of Feb 1, 2024'
}
});
Check Execution Status
Get the status of an email execution:
const status = await sendmator.email.getExecutionStatus('execution-uuid');
console.log('Status:', status.data.status);
console.log('Sent at:', status.data.executed_at);
console.log('Recipients:', status.data.recipient_count);
List Email Executions
List all email executions with pagination:
const executions = await sendmator.email.listExecutions({
page: 1,
limit: 20
});
console.log('Total executions:', executions.data.total);
executions.data.executions.forEach(execution => {
console.log(`${execution.template_key} - ${execution.status}`);
});
Examples
Welcome Email
async function sendWelcomeEmail(userEmail: string, userName: string) {
await sendmator.email.send({
recipient_type: 'direct_email',
direct_email: userEmail,
template_key: 'welcome-email',
variables: {
name: userName,
loginUrl: 'https://app.example.com/login',
supportEmail: 'support@example.com'
},
metadata: {
event: 'user_signup',
timestamp: new Date().toISOString()
}
});
}
Order Confirmation
async function sendOrderConfirmation(externalId: string, order: any) {
await sendmator.email.send({
recipient_type: 'contact',
contact_external_id: externalId,
template_key: 'order-confirmation',
variables: {
orderNumber: order.number,
orderDate: order.date,
items: order.items,
total: order.total,
shippingAddress: order.shippingAddress,
trackingUrl: order.trackingUrl
},
metadata: {
order_id: order.id,
order_number: order.number
}
});
}
Newsletter Campaign
async function sendNewsletter() {
await sendmator.email.send({
recipient_type: 'tag',
tag: ['newsletter', 'active'],
template_key: 'monthly-newsletter',
variables: {
month: 'January',
year: '2024',
headline: 'New Features Released',
articles: [
{ title: 'Feature 1', url: 'https://...' },
{ title: 'Feature 2', url: 'https://...' }
]
},
metadata: {
campaign: 'newsletter',
month: '2024-01'
}
});
}
Password Reset
async function sendPasswordReset(email: string, resetToken: string) {
const resetUrl = `https://app.example.com/reset-password?token=${resetToken}`;
await sendmator.email.send({
recipient_type: 'direct_email',
direct_email: email,
template_key: 'password-reset',
variables: {
resetUrl,
expiresIn: '1 hour'
},
metadata: {
event: 'password_reset_requested'
}
});
}
Raw HTML Email
async function sendCustomEmail(email: string) {
const htmlContent = `
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial, sans-serif; }
.header { background: #007bff; color: white; padding: 20px; }
.content { padding: 20px; }
</style>
</head>
<body>
<div class="header">
<h1>Custom Email</h1>
</div>
<div class="content">
<p>This is a custom HTML email.</p>
<a href="https://example.com">Click here</a>
</div>
</body>
</html>
`;
await sendmator.email.send({
recipient_type: 'direct_email',
direct_email: email,
subject: 'Custom HTML Email',
content: htmlContent,
plain_text_content: 'This is a custom HTML email. Visit https://example.com',
from: 'noreply@example.com',
from_name: 'Example Team'
});
}
Error Handling
import { SendmatorError } from '@sendmator/node';
try {
await sendmator.email.send({
recipient_type: 'direct_email',
direct_email: 'user@example.com',
template_key: 'non-existent-template'
});
} catch (error) {
if (error instanceof SendmatorError) {
if (error.statusCode === 404) {
console.error('Template not found');
} else if (error.statusCode === 400) {
console.error('Invalid email data:', error.message);
} else {
console.error('Email failed:', error.message);
}
}
}
Best Practices
- Use Templates - Templates are easier to manage and update than raw HTML
- Provide Plain Text - Always include plain text content for better deliverability
- Personalize - Use variables to personalize emails
- Track Metadata - Add metadata for analytics and tracking
- Handle Errors - Implement proper error handling
- Schedule Wisely - Use triggerAt for time-sensitive emails
- Test First - Use sandbox/test mode before production sends
- Reply-To Address - Always provide a reply-to address for customer emails
Recipient Types
| Type | Use Case | Required Field |
|---|---|---|
direct_email | Send to email without creating contact | direct_email |
contact | Send to existing contact | contact_external_id |
tag | Send to contacts with specific tags | tag (array) |
all | Send to all contacts | None |
Next Steps
- SMS SDK - Send SMS messages
- WhatsApp SDK - Send WhatsApp messages
- Contacts SDK - Manage contacts
- OTP SDK - Verify users with OTP