Real-World Examples
Complete, production-ready examples showing how to integrate Sendmator into your application. These examples demonstrate real-world use cases from start to finish.
Complete User Signup Flow
This example shows a complete user registration flow with email verification, database integration, and welcome email. This is one of the most common use cases for Sendmator.
Flow Overview:
- Send OTP for email verification
- Verify the OTP code
- Add user to your database
- Create contact in Sendmator
- Send personalized welcome email
Prerequisites
npm install @sendmator/node dotenv
Complete Implementation
import Sendmator from '@sendmator/node';
import * as dotenv from 'dotenv';
dotenv.config();
// Initialize Sendmator client
const sendmator = new Sendmator({
apiKey: process.env.SENDMATOR_API_KEY!,
teamId: process.env.SENDMATOR_TEAM_ID,
});
// Mock database (replace with your actual database)
const database = {
users: [] as any[],
async createUser(userData: any) {
const user = {
id: `user_${Date.now()}`,
...userData,
createdAt: new Date().toISOString(),
};
this.users.push(user);
return user;
},
async getUserByEmail(email: string) {
return this.users.find((u) => u.email === email);
},
};
// Complete signup flow
async function completeUserSignupFlow(
email: string,
firstName: string,
lastName: string
) {
try {
// ============================================
// STEP 1: Send OTP for email verification
// ============================================
console.log('📧 Sending OTP to email...');
const otpResponse = await sendmator.otp.send({
channels: ['email'],
recipients: {
email: email,
},
sandbox_mode: true, // Set to false in production
add_contact: false, // We'll add manually after verification
});
const sessionToken = otpResponse.data.session_token;
const testOTP = otpResponse.data.otps?.email; // Only in sandbox mode
console.log('✓ OTP sent successfully');
console.log('Session ID:', otpResponse.data.session_id);
// In real app, user receives OTP via email and enters it
// For this example, we use the sandbox OTP
const userEnteredOTP = testOTP || '123456';
// ============================================
// STEP 2: Verify the OTP code
// ============================================
console.log('✅ Verifying OTP...');
const verifyResponse = await sendmator.otp.verify({
session_token: sessionToken,
otps: {
email: userEnteredOTP,
},
});
if (!verifyResponse.data.verified) {
throw new Error('OTP verification failed');
}
console.log('✓ OTP verified - email confirmed');
// ============================================
// STEP 3: Add user to your database
// ============================================
console.log('💾 Adding user to database...');
const newUser = await database.createUser({
email: email,
firstName: firstName,
lastName: lastName,
emailVerified: true,
verifiedAt: new Date().toISOString(),
});
console.log('✓ User created in database');
console.log('User ID:', newUser.id);
// ============================================
// STEP 4: Create contact in Sendmator
// ============================================
console.log('👤 Adding user as a contact...');
const contactResponse = await sendmator.contacts.create({
email: email,
first_name: firstName,
last_name: lastName,
external_id: newUser.id, // Link to your database
tags: ['new-user', 'email-verified'],
custom_fields: {
signup_date: newUser.createdAt,
source: 'website',
},
metadata: {
user_id: newUser.id,
verified_via: 'otp',
},
});
console.log('✓ Contact created in Sendmator');
console.log('Contact ID:', contactResponse.data.id);
// ============================================
// STEP 5: Send welcome email
// ============================================
console.log('📬 Sending welcome email...');
const welcomeResponse = await sendmator.email.sendToContact(
newUser.id, // external_id
{
template_key: 'welcome-email', // Create this in dashboard
subject: `Welcome to Sendmator, ${firstName}!`,
variables: {
first_name: firstName,
last_name: lastName,
signup_date: new Date().toLocaleDateString(),
},
}
);
console.log('✓ Welcome email sent');
console.log('Trigger ID:', welcomeResponse.data.trigger_id);
// ============================================
// DONE!
// ============================================
console.log('🎉 User signup flow completed successfully');
return {
success: true,
user: newUser,
contact: contactResponse.data,
welcomeEmailSent: true,
};
} catch (error: any) {
console.error('❌ Error in signup flow:', error.message);
throw error;
}
}
// Run the example
async function main() {
const result = await completeUserSignupFlow(
'newuser@example.com',
'John',
'Doe'
);
console.log('Final Result:', result);
}
main();
Expected Output
📧 Sending OTP to email...
✓ OTP sent successfully
Session ID: otp_session_abc123
✅ Verifying OTP...
✓ OTP verified - email confirmed
💾 Adding user to database...
✓ User created in database
User ID: user_1234567890
👤 Adding user as a contact...
✓ Contact created in Sendmator
Contact ID: contact_xyz789
📬 Sending welcome email...
✓ Welcome email sent
Trigger ID: trigger_def456
🎉 User signup flow completed successfully
Production Considerations
Environment Variables:
SENDMATOR_API_KEY=your_api_key_here
SENDMATOR_TEAM_ID=your_team_id_here
Set sandbox_mode to false:
const otpResponse = await sendmator.otp.send({
channels: ['email'],
recipients: { email: email },
sandbox_mode: false, // Production mode
add_contact: false,
});
Create the welcome email template:
- Go to app.sendmator.com
- Navigate to Templates
- Create a template with key
welcome-email - Add variables:
{{first_name}},{{last_name}},{{signup_date}}
Error Handling
async function signupWithErrorHandling(email: string, firstName: string, lastName: string) {
try {
// Send OTP
const otpResponse = await sendmator.otp.send({
channels: ['email'],
recipients: { email },
});
return { success: true, sessionToken: otpResponse.data.session_token };
} catch (error: any) {
if (error.response?.status === 429) {
// Rate limit exceeded
return {
success: false,
error: 'Too many attempts. Please try again later.'
};
}
if (error.response?.status === 400) {
// Invalid email
return {
success: false,
error: 'Invalid email address.'
};
}
// General error
return {
success: false,
error: 'Failed to send verification code. Please try again.'
};
}
}
Multi-Channel OTP Verification
Send OTP across multiple channels and let users verify via their preferred method.
async function multiChannelOTP(email: string, phone: string) {
// Send OTP to both email and SMS
const otpResponse = await sendmator.otp.send({
channels: ['email', 'sms'],
recipients: {
email: email,
phone_number: phone,
},
});
const sessionToken = otpResponse.data.session_token;
// User can verify with either channel
const verifyResponse = await sendmator.otp.verify({
session_token: sessionToken,
otps: {
email: '123456', // User enters OTP from email
// OR
// sms: '123456', // User enters OTP from SMS
},
});
return verifyResponse.data.verified;
}
Progressive OTP Verification
Start with email, fallback to SMS if needed.
async function progressiveVerification(email: string, phone: string) {
// Step 1: Try email first
const emailOTP = await sendmator.otp.send({
channels: ['email'],
recipients: { email },
});
// If user doesn't receive email, they can request SMS
const addSMS = await sendmator.otp.progressive({
session_token: emailOTP.data.session_token,
channel: 'sms',
phone_number: phone,
});
console.log('SMS OTP sent as fallback');
// User can verify with either
const verify = await sendmator.otp.verify({
session_token: emailOTP.data.session_token,
otps: {
sms: '123456', // Verify with SMS code
},
});
return verify.data.verified;
}
Bulk Contact Import
Import multiple contacts at once from CSV or database.
async function bulkImportContacts(users: any[]) {
const results = {
success: 0,
failed: 0,
errors: [] as any[],
};
for (const user of users) {
try {
await sendmator.contacts.create({
email: user.email,
first_name: user.firstName,
last_name: user.lastName,
external_id: user.id,
tags: ['imported', user.source],
custom_fields: {
imported_at: new Date().toISOString(),
},
});
results.success++;
} catch (error: any) {
results.failed++;
results.errors.push({
email: user.email,
error: error.message,
});
}
}
return results;
}
// Usage
const users = [
{ id: '1', email: 'user1@example.com', firstName: 'John', lastName: 'Doe', source: 'web' },
{ id: '2', email: 'user2@example.com', firstName: 'Jane', lastName: 'Smith', source: 'mobile' },
// ... more users
];
const importResults = await bulkImportContacts(users);
console.log(`✓ Imported: ${importResults.success}`);
console.log(`✗ Failed: ${importResults.failed}`);
Transaction Email with Order Details
Send order confirmation with dynamic content.
async function sendOrderConfirmation(orderId: string, userId: string) {
// Fetch order details from your database
const order = await database.getOrder(orderId);
await sendmator.email.sendToContact(
userId, // external_id
{
template_key: 'order-confirmation',
subject: `Order Confirmation #${order.orderNumber}`,
variables: {
order_number: order.orderNumber,
order_date: order.createdAt,
total_amount: order.total,
items: order.items.map(item => ({
name: item.name,
quantity: item.quantity,
price: item.price,
})),
shipping_address: order.shippingAddress,
tracking_url: order.trackingUrl,
},
}
);
console.log('Order confirmation sent');
}
Password Reset Flow
Complete password reset with OTP verification.
async function passwordResetFlow(email: string) {
// Check if user exists
const user = await database.getUserByEmail(email);
if (!user) {
// Don't reveal if user exists (security)
return { success: true };
}
// Send OTP for verification
const otpResponse = await sendmator.otp.send({
channels: ['email'],
recipients: { email },
add_contact: false,
});
return {
success: true,
sessionToken: otpResponse.data.session_token,
};
}
async function verifyAndResetPassword(
sessionToken: string,
otpCode: string,
newPassword: string
) {
// Verify OTP
const verifyResponse = await sendmator.otp.verify({
session_token: sessionToken,
otps: { email: otpCode },
});
if (!verifyResponse.data.verified) {
throw new Error('Invalid verification code');
}
// Update password in your database
await database.updatePassword(
verifyResponse.data.recipients.email,
newPassword
);
// Send confirmation email
await sendmator.email.send({
to: verifyResponse.data.recipients.email,
template_key: 'password-reset-confirmation',
subject: 'Your password has been reset',
variables: {
reset_date: new Date().toLocaleString(),
},
});
return { success: true };
}
WhatsApp Business Messaging
Send WhatsApp messages using approved templates.
async function sendWhatsAppNotification(userId: string, orderStatus: string) {
const user = await database.getUser(userId);
await sendmator.whatsapp.sendToContact(
userId, // external_id
{
template_key: 'order_status_update', // Approved WhatsApp template
variables: {
customer_name: user.firstName,
order_number: '12345',
status: orderStatus,
},
}
);
console.log('WhatsApp notification sent');
}
Complete Source Code
All examples are available in our GitHub repository:
Repository: sendmator-examples
# Clone the repository
git clone https://github.com/sendmator/sendmator-examples.git
# Install dependencies
cd sendmator-examples
npm install
# Set up environment
cp .env.example .env
# Edit .env with your API credentials
# Run the complete signup example
npm start
Next Steps
- OTP API Reference - Detailed OTP documentation
- Contacts API - Managing contacts
- Email Templates - Creating email templates
- Rate Limits - Understanding rate limits
- Node.js SDK - Complete SDK reference
Need Help?
- Join our Discord Community
- Email us at support@sendmator.com
- Check out API Status