Skip to main content

Sending Emails

This guide covers best practices for sending emails with Sendmator, from simple transactional emails to complex campaigns.

Basic Email Sending

Simple Text Email

await sendmator.emails.send({
to: 'user@example.com',
from: 'hello@yourapp.com',
subject: 'Welcome!',
text: 'Thanks for signing up for our service.'
});

HTML Email with Fallback

await sendmator.emails.send({
to: 'user@example.com',
from: 'hello@yourapp.com',
subject: 'Welcome to our platform!',
html: `
<div style="font-family: Arial, sans-serif;">
<h1>Welcome!</h1>
<p>Thanks for signing up. We're excited to have you on board.</p>
<a href="https://yourapp.com/dashboard" style="background: #007bff; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;">Get Started</a>
</div>
`,
text: 'Welcome! Thanks for signing up. Get started at: https://yourapp.com/dashboard'
});

Email Personalization

Using Templates

// First, create a template
const template = await sendmator.templates.create({
name: 'user-welcome',
subject: 'Welcome to {{company_name}}, {{user_name}}!',
html: `
<h1>Welcome, {{user_name}}!</h1>
<p>Thanks for joining {{company_name}}.</p>
<p>Your account type: {{account_type}}</p>
<a href="{{dashboard_url}}">Access Dashboard</a>
`
});

// Then use it to send personalized emails
await sendmator.emails.send({
to: 'john@example.com',
template: 'user-welcome',
template_data: {
user_name: 'John Doe',
company_name: 'YourApp Inc.',
account_type: 'Premium',
dashboard_url: 'https://yourapp.com/dashboard'
}
});

Advanced Features

Multiple Recipients

// CC and BCC
await sendmator.emails.send({
to: 'primary@example.com',
cc: ['manager@example.com'],
bcc: ['archive@yourcompany.com'],
from: 'notifications@yourapp.com',
subject: 'Project Update',
html: '<h1>Project Status</h1><p>The project is on track.</p>'
});

Email with Attachments

const fs = require('fs');

// Read file and convert to base64
const pdfContent = fs.readFileSync('invoice.pdf');
const base64Content = pdfContent.toString('base64');

await sendmator.emails.send({
to: 'customer@example.com',
from: 'billing@yourapp.com',
subject: 'Your Invoice',
html: '<p>Please find your invoice attached.</p>',
attachments: [{
filename: 'invoice.pdf',
content: base64Content,
content_type: 'application/pdf'
}]
});

Best Practices

1. Always Include Both HTML and Text

// Good practice
await sendmator.emails.send({
to: 'user@example.com',
from: 'hello@yourapp.com',
subject: 'Welcome!',
html: '<h1>Welcome!</h1><p>Thanks for signing up.</p>',
text: 'Welcome! Thanks for signing up.'
});

2. Use Meaningful From Addresses

// Good
from: 'notifications@yourapp.com'
from: 'support@yourapp.com'
from: 'billing@yourapp.com'

// Avoid
from: 'noreply@yourapp.com'
from: 'donotreply@yourapp.com'

3. Handle Errors Gracefully

try {
const result = await sendmator.emails.send({
to: 'user@example.com',
from: 'hello@yourapp.com',
subject: 'Welcome!',
html: '<h1>Welcome!</h1>'
});

console.log('Email sent:', result.id);
} catch (error) {
console.error('Failed to send email:', error.message);

// Log for debugging
logger.error('Email send failed', {
to: 'user@example.com',
error: error.message,
code: error.code
});

// Don't fail the user flow for email errors
// Continue with the rest of your application logic
}

4. Use Tags for Organization

await sendmator.emails.send({
to: 'user@example.com',
from: 'hello@yourapp.com',
subject: 'Welcome!',
html: '<h1>Welcome!</h1>',
tags: ['onboarding', 'welcome', 'transactional'],
metadata: {
user_id: '12345',
signup_flow: 'web'
}
});

Bulk Email Sending

Sequential Sending

const users = [
{ email: 'user1@example.com', name: 'John' },
{ email: 'user2@example.com', name: 'Jane' },
{ email: 'user3@example.com', name: 'Bob' }
];

for (const user of users) {
try {
await sendmator.emails.send({
to: user.email,
template: 'newsletter',
template_data: { name: user.name }
});
console.log(`Email sent to ${user.email}`);
} catch (error) {
console.error(`Failed to send to ${user.email}:`, error.message);
}
}

Parallel Sending (Faster)

const users = [
{ email: 'user1@example.com', name: 'John' },
{ email: 'user2@example.com', name: 'Jane' },
{ email: 'user3@example.com', name: 'Bob' }
];

const emailPromises = users.map(user =>
sendmator.emails.send({
to: user.email,
template: 'newsletter',
template_data: { name: user.name }
}).catch(error => {
console.error(`Failed to send to ${user.email}:`, error.message);
return null; // Don't fail the entire batch
})
);

const results = await Promise.all(emailPromises);
const successCount = results.filter(r => r !== null).length;
console.log(`Sent ${successCount}/${users.length} emails`);

Monitoring and Analytics

Track Email Status

// Send email
const result = await sendmator.emails.send({
to: 'user@example.com',
from: 'hello@yourapp.com',
subject: 'Welcome!',
html: '<h1>Welcome!</h1>'
});

// Check status later
setTimeout(async () => {
const email = await sendmator.emails.retrieve(result.id);
console.log('Email status:', email.status);
console.log('Events:', email.events);
}, 60000); // Check after 1 minute

Using Webhooks for Real-time Updates

// Set up webhook endpoint
app.post('/webhooks/sendmator', (req, res) => {
const event = req.body;

switch (event.type) {
case 'email.delivered':
console.log(`Email ${event.data.id} delivered to ${event.data.to}`);
// Update your database
break;

case 'email.opened':
console.log(`Email ${event.data.id} opened by ${event.data.to}`);
// Track engagement
break;

case 'email.bounced':
console.log(`Email ${event.data.id} bounced: ${event.data.bounce_reason}`);
// Handle bounce (maybe remove from list)
break;
}

res.status(200).send('OK');
});

Common Patterns

Welcome Email Flow

async function sendWelcomeEmail(user) {
try {
const result = await sendmator.emails.send({
to: user.email,
from: 'welcome@yourapp.com',
template: 'welcome-series-1',
template_data: {
user_name: user.name,
verification_url: generateVerificationUrl(user.id),
dashboard_url: 'https://yourapp.com/dashboard'
},
tags: ['onboarding', 'welcome'],
metadata: {
user_id: user.id,
sequence: 'welcome',
step: 1
}
});

// Schedule follow-up emails
scheduleFollowUp(user.id, result.id);

return result;
} catch (error) {
console.error('Welcome email failed:', error);
throw error;
}
}

Password Reset

async function sendPasswordReset(email, resetToken) {
const resetUrl = `https://yourapp.com/reset-password?token=${resetToken}`;

return await sendmator.emails.send({
to: email,
from: 'security@yourapp.com',
subject: 'Reset your password',
html: `
<h2>Reset Your Password</h2>
<p>Click the link below to reset your password:</p>
<a href="${resetUrl}" style="background: #007bff; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;">Reset Password</a>
<p>This link expires in 1 hour.</p>
<p>If you didn't request this, please ignore this email.</p>
`,
text: `Reset your password: ${resetUrl}\n\nThis link expires in 1 hour. If you didn't request this, please ignore this email.`,
tags: ['security', 'password-reset']
});
}

Troubleshooting

Common Issues

  1. Emails going to spam

    • Always include both HTML and text versions
    • Use a consistent "from" address
    • Avoid spam trigger words
    • Set up proper SPF/DKIM records
  2. High bounce rates

    • Validate email addresses before sending
    • Remove bounced addresses from your list
    • Use double opt-in for subscriptions
  3. Low open rates

    • Write compelling subject lines
    • Optimize send times
    • Segment your audience
    • A/B test your emails

For more detailed troubleshooting, see our Error Handling Guide.