SendMailCommand
Overview
SendMailCommand sends email notifications with support for HTML content, multiple recipients, BCC, attachments, and template-based document generation. It integrates with the email provider configured in your tenant settings.
When to Use
✅ Use SendMailCommand for:
- Sending transactional emails (receipts, confirmations, notifications)
- Sending HTML-formatted emails with templates
- Sending emails with document attachments
- Sending emails to multiple recipients with BCC
- Automated email workflows in business processes
❌ Don't use for:
- SMS notifications (use
SendSMSCommand) - Real-time chat messages
- System-to-system notifications (use APIs)
Syntax
Basic Email (doCmd)
var result = doCmd('SendMailCommand', {
Data: {
subject: 'Loan Application Approved',
email: ['customer@example.com'],
message: '<h1>Congratulations!</h1><p>Your loan has been approved.</p>',
sender: 'no-reply@bank.com'
}
});
With Template and Document Attachments
var result = doCmd('SendMailCommand', {
Data: {
subject: 'Monthly Account Statement',
email: ['customer@example.com', 'spouse@example.com'],
bcc: ['compliance@bank.com'],
sender: 'statements@bank.com',
reference: 'STMT-2024-001',
templateId: 'MONTHLY_STATEMENT_EMAIL',
context: {
customerName: context.customerName,
accountNumber: context.accountNumber,
balance: context.balance,
statementMonth: 'January 2024'
},
documentTemplateIds: ['ACCOUNT_STATEMENT_PDF', 'TRANSACTION_DETAIL_PDF']
}
});
JSON Configuration
{
"commandName": "SendMailCommand",
"parameters": {
"Data": {
"subject": "Loan Approval Notification",
"email": ["customer@example.com"],
"message": "<html><body><h1>Approved</h1></body></html>",
"sender": "loans@bank.com",
"bcc": ["audit@bank.com"],
"attachments": ["/documents/loan-agreement.pdf"],
"reference": "LOAN-2024-12345"
}
}
}
Parameters
Data Object
| Parameter | Type | Required | Description |
|---|---|---|---|
| subject | string | ✅ Yes | Email subject line |
| string[] | ✅ Yes | List of recipient email addresses | |
| message | string | Conditional | HTML email body (required if no templateId) |
| templateId | string | Conditional | Template ID from HtmlTemplateDefinition table (required if no message) |
| context | object | No | Data for template rendering (used with templateId) |
| sender | string | No | Sender email address (defaults to system sender) |
| bcc | string[] | No | Blind carbon copy recipients |
| attachments | string[] | No | List of file paths for static attachments |
| documentTemplateIds | string[] | No | Document template IDs to generate and attach |
| reference | string | No | Unique reference for tracking |
How It Works
1. Simple Email Flow
SendMailCommand → Email Provider → Recipient
2. Template-Based Email Flow
SendMailCommand
├─> Fetch HtmlTemplateDefinition (by templateId)
├─> RenderHtmlCommand (template + context)
├─> Generated HTML becomes message
└─> Email Provider → Recipient
3. Email with Generated Documents
SendMailCommand
├─> For each documentTemplateId:
│ ├─> Fetch DocumentTemplate
│ ├─> DocumentRenderCommand (template + context)
│ └─> Generated PDF/document
├─> Attach all generated documents
└─> Email Provider → Recipient
Return Value
Success Response
{
"isSuccessful": true,
"message": "Mail has been sent successfully.",
"statusCode": 200
}
Error Response
{
"isSuccessful": false,
"message": "Failed to send email: Invalid email address",
"statusCode": 400,
"data": {
"error": "Invalid email format",
"invalidEmails": ["not-an-email"]
}
}
Examples
Example 1: Simple Notification Email
// Send a simple HTML email
var result = doCmd('SendMailCommand', {
Data: {
subject: 'Password Reset Successful',
email: [context.userEmail],
message: `
<html>
<body style="font-family: Arial, sans-serif;">
<h2>Password Reset Confirmation</h2>
<p>Hello ${context.userName},</p>
<p>Your password has been successfully reset.</p>
<p>If you did not request this change, please contact support immediately.</p>
</body>
</html>
`,
sender: 'security@bank.com',
reference: 'PWD-RESET-' + context.userId
}
});
if (result.isSuccessful) {
logger.info('Password reset email sent to: ' + context.userEmail);
}
Example 2: Template-Based Email
// Use a pre-defined email template
var result = doCmd('SendMailCommand', {
Data: {
subject: 'Loan Application Status Update',
email: [context.applicantEmail],
templateId: 'LOAN_STATUS_EMAIL',
context: {
applicantName: context.applicantName,
loanAmount: context.loanAmount,
status: context.applicationStatus,
nextSteps: context.nextSteps,
referenceNumber: context.applicationId
},
sender: 'loans@bank.com'
}
});
// Template LOAN_STATUS_EMAIL in HtmlTemplateDefinition:
// <html>
// <body>
// <h1>Loan Application Update</h1>
// <p>Dear {{applicantName}},</p>
// <p>Your loan application for {{loanAmount}} is now <strong>{{status}}</strong>.</p>
// <p>Reference: {{referenceNumber}}</p>
// <h3>Next Steps:</h3>
// <p>{{nextSteps}}</p>
// </body>
// </html>
Example 3: Email with Multiple Recipients and BCC
// Send to multiple recipients with audit trail
var result = doCmd('SendMailCommand', {
Data: {
subject: 'Monthly Board Report - January 2024',
email: [
'ceo@bank.com',
'cfo@bank.com',
'coo@bank.com'
],
bcc: [
'compliance@bank.com',
'audit@bank.com'
],
message: context.boardReportHtml,
sender: 'board-secretary@bank.com',
reference: 'BOARD-REPORT-2024-01'
}
});
Example 4: Email with Static Attachments
// Send email with pre-existing document attachments
var result = doCmd('SendMailCommand', {
Data: {
subject: 'Contract Documents for Review',
email: [context.clientEmail],
message: '<h2>Please review the attached documents</h2>',
sender: 'contracts@bank.com',
attachments: [
'/documents/contracts/loan-agreement-2024.pdf',
'/documents/contracts/terms-and-conditions.pdf'
]
}
});
Example 5: Email with Generated Document Attachments
// Generate documents dynamically and attach to email
var result = doCmd('SendMailCommand', {
Data: {
subject: 'Your Monthly Account Statement',
email: [context.customerEmail],
templateId: 'ACCOUNT_STATEMENT_EMAIL',
context: {
customerName: context.customerName,
accountNumber: context.accountNumber,
statementPeriod: 'January 2024',
balance: context.currentBalance
},
documentTemplateIds: [
'ACCOUNT_STATEMENT_PDF', // Main statement
'TRANSACTION_DETAILS_PDF', // Transaction list
'FEE_SCHEDULE_PDF' // Fee breakdown
],
sender: 'statements@bank.com'
}
});
// The system will:
// 1. Render email HTML using ACCOUNT_STATEMENT_EMAIL template
// 2. Generate ACCOUNT_STATEMENT_PDF using context
// 3. Generate TRANSACTION_DETAILS_PDF using context
// 4. Generate FEE_SCHEDULE_PDF using context
// 5. Attach all 3 PDFs to the email
// 6. Send the email
Example 6: Workflow Integration
// Complete loan approval notification workflow
function sendLoanApprovalEmail(loanId) {
// 1. Get loan details
var loan = doCmd('RetrieveLoanByIdQuery', {
Data: { id: loanId }
});
if (!loan.isSuccessful) {
throw new Error('Loan not found');
}
// 2. Get customer details
var customer = doCmd('RetrieveCustomerByIdQuery', {
Data: { id: loan.data.customerId }
});
// 3. Send approval email with loan agreement
var emailResult = doCmd('SendMailCommand', {
Data: {
subject: `Loan Approved - ${loan.data.loanType}`,
email: [customer.data.email],
templateId: 'LOAN_APPROVAL_EMAIL',
context: {
customerName: customer.data.fullName,
loanAmount: loan.data.approvedAmount,
interestRate: loan.data.interestRate,
tenure: loan.data.tenureMonths,
monthlyPayment: loan.data.monthlyInstallment,
approvalDate: new Date().toLocaleDateString(),
loanId: loan.data.id
},
documentTemplateIds: [
'LOAN_AGREEMENT_PDF',
'AMORTIZATION_SCHEDULE_PDF'
],
bcc: ['loans-approved@bank.com'],
sender: 'loans@bank.com',
reference: 'LOAN-APPROVAL-' + loanId
}
});
if (emailResult.isSuccessful) {
// 4. Log email sent
doCmd('InsertTableCommand', {
Data: {
table: 'tblEmailLog',
values: {
LoanId: loanId,
EmailType: 'LOAN_APPROVAL',
SentDate: new Date(),
Status: 'SENT'
}
}
});
}
return emailResult;
}
Integration with Other Commands
Using RenderHtmlCommand for Template Rendering
// Manual template rendering (if you need the HTML separately)
var htmlResult = doCmd('RenderHtmlCommand', {
Data: {
template: '<h1>Welcome {{name}}</h1>',
data: { name: 'John Doe' }
}
});
// Then use the rendered HTML in email
var emailResult = doCmd('SendMailCommand', {
Data: {
subject: 'Welcome Email',
email: ['john@example.com'],
message: htmlResult.data.html
}
});
Using DocumentRenderCommand for Attachments
// Pre-generate document before sending email
var docResult = doCmd('DocumentRenderCommand', {
Data: {
templateId: 'CONTRACT_PDF',
context: { contractId: '12345' }
}
});
// Send email with pre-generated document
var emailResult = doCmd('SendMailCommand', {
Data: {
subject: 'Contract Document',
email: ['client@example.com'],
message: '<p>Please find attached contract</p>',
attachments: [docResult.data.filePath]
}
});
Use Cases
1. Customer Onboarding
Send welcome email with account details and terms document:
doCmd('SendMailCommand', {
Data: {
templateId: 'WELCOME_EMAIL',
documentTemplateIds: ['ACCOUNT_TERMS_PDF', 'WELCOME_PACK_PDF'],
context: { /* customer data */ }
}
});
2. Transaction Notifications
Alert customers about large transactions:
doCmd('SendMailCommand', {
Data: {
templateId: 'TRANSACTION_ALERT',
context: {
amount: transaction.amount,
type: transaction.type,
balance: account.balance
}
}
});
3. Compliance Reporting
Send regulatory reports to authorities:
doCmd('SendMailCommand', {
Data: {
subject: 'Monthly Compliance Report',
email: ['regulator@centralbank.com'],
bcc: ['compliance@bank.com'],
documentTemplateIds: ['COMPLIANCE_REPORT_PDF']
}
});
Error Handling
Common Errors
| Error | Cause | Solution |
|---|---|---|
| "Subject is required" | Missing subject field | Provide subject parameter |
| "Email list is required" | Missing email array | Provide at least one email address |
| "Message or templateId required" | Missing both message and templateId | Provide either message or templateId |
| "Template not found" | Invalid templateId | Check HtmlTemplateDefinition table |
| "Invalid email format" | Malformed email address | Validate email format |
| "Attachment not found" | Invalid file path | Verify file exists at path |
| "Document generation failed" | Template rendering error | Check document template and context |
Error Handling Example
try {
var result = doCmd('SendMailCommand', {
Data: {
subject: 'Important Notice',
email: [context.customerEmail],
templateId: 'NOTICE_EMAIL',
context: context
}
});
if (!result.isSuccessful) {
logger.error('Email failed: ' + result.message);
// Retry logic
if (result.message.includes('Template not found')) {
// Fall back to simple message
result = doCmd('SendMailCommand', {
Data: {
subject: 'Important Notice',
email: [context.customerEmail],
message: '<p>Please contact us for important information</p>'
}
});
}
}
} catch (error) {
logger.error('Email error: ' + error.message);
// Handle critical failure
}
Best Practices
1. Email Address Validation
function isValidEmail(email) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}
var emails = [context.email].filter(isValidEmail);
2. Template Organization
- Store reusable templates in HtmlTemplateDefinition
- Use consistent naming:
{MODULE}_{TYPE}_EMAIL - Version templates:
LOAN_APPROVAL_EMAIL_V2
3. Context Preparation
// Prepare clean context object
var emailContext = {
customerName: context.customerName || 'Valued Customer',
amount: formatCurrency(context.amount),
date: formatDate(new Date()),
reference: context.transactionId
};
4. Audit Trail
Always include reference parameter for tracking:
reference: 'EMAIL-' + context.processId + '-' + Date.now()
5. BCC for Compliance
Include compliance/audit emails in BCC:
bcc: ['compliance@bank.com', 'audit@bank.com']
Performance Tips
- Batch Recipients: Send one email to multiple recipients instead of multiple emails
- Cache Templates: Templates are cached after first load
- Async Processing: Email sending is asynchronous, doesn't block process
- Document Generation: Pre-generate frequently used documents
- Template Size: Keep email templates under 100KB for best performance
Related Commands
- SendSMSCommand - Send SMS notifications
- RenderHtmlCommand - Render HTML templates
DocumentRenderCommand- Generate document attachmentsInsertTableCommand- Log sent emails
API Endpoint
POST /api/bpm/execute-command
{
"commandName": "SendMailCommand",
"parameters": {
"Data": {
"subject": "Test Email",
"email": ["test@example.com"],
"message": "<h1>Test</h1>"
}
}
}
Configuration
Email Provider Settings
Email provider is configured in tenant configuration:
- SMTP Server
- SMTP Port
- Username/Password
- SSL/TLS Settings
- Default Sender Address
Template Storage
Templates are stored in:
- HtmlTemplateDefinition table for email templates
- DocumentTemplate table for document templates
Version History
- v2.0: Added documentTemplateIds for dynamic attachments
- v1.5: Added templateId support with RenderHtmlCommand integration
- v1.0: Initial release with basic email functionality
See Also
- Email Template Guide - Creating HTML email templates
- Document Generation - Generating PDF attachments
- Process Automation - Using emails in workflows