- Automated ERP Communication: Designing branded, dynamic email communications for workflows, order confirmations, and notifications.
- SMTP & Graph Setup: Configuring Email Parameters with Microsoft 365 Exchange Online or external SMTP relays.
- Template Hierarchy: Comparing System Email Templates (tenant-wide) with Organization Email Templates (legal-entity specific).
- Dynamic Token Placeholders: Injecting single-value placeholders (e.g. customer name) and dynamic HTML repeating tables.
- X++ Email Dispatch Engine: Leveraging
SysEmailMessageTableandSysMailerMessageBuilderfor high-reliability dispatch.
Overview: Enterprise Communication Architecture
Automated email communication is an essential component of modern enterprise ERP workflows. From order confirmations to workflow approvals and financial alerts, Dynamics 365 Finance & Operations provides a native templating framework that supports branded HTML messaging and dynamic placeholder tokens.
“Decoupling email content into HTML templates allows functional teams to modify branding and messaging without triggering code releases or recompiling models.”
Step 1: Configuring Email Parameters
Navigate to System administration > Setup > Email > Email parameters. Configure your outbound mail provider (SMTP or Microsoft 365 Exchange Online):
Step 2: Testing Email Connection in X++
Execute a simple X++ runnable class to verify that the outbound mail server is successfully accepting connections from your D365FO environment:
internal final class SendEmailToTestConnection
{
public static void main(Args _args)
{
str Id = "177";
str name = "Muhammad Haroon";
str body = "The purpose of this email is to test Connection!";
SendEmailToTestConnection::mailerSender(Id, name, body);
}
public static void mailerSender(str _id, str _name, str _body)
{
SysMailerMessageBuilder messageBuilder = new SysMailerMessageBuilder();
Email toEmail;
Email fromEmail;
try
{
fromEmail = "Sender email address";
toEmail = "Receiver email address
messageBuilder.setBody("The email Id is: " + _id + "\n" + "Sent by: " + _name + "\n" + _body, false);
messageBuilder.setSubject("Email test from D365");
messageBuilder.addTo(toEmail);
messageBuilder.setFrom(fromEmail);
// Sends a message interactively, allowing the user to view and modify the message before
SysMailerFactory::sendNonInteractive(messageBuilder.getMessage());
// Try using sendNonInteractive method too
Info("Email sent successfully");
}
catch (Exception::Error)
{
throw error("@SYS33567");
}
}
}
Step 3: Email Template with Single Record Placeholders
Create an HTML template containing scalar placeholders (such as %id%, %name%):
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
font-family: Calibri;
table-layout: fixed;
width: 600px;
}
</style>
<meta charset="UTF-8">
<h1>Order created</h1>
<p><strong>Order number: %salesid%.</strong></p>
</head>
<tbody>
<h1>Dear %customername%,</h1>
<p>Thank you for shopping with Adventure Works! Your order has been created and is being processed. See below for details.</p>
<p><strong>Shipping information</strong></p>
<p>%customername%</p>
<p>%deliveryaddress%</p>
<p><strong>Expected ship date:</strong></p>
<p>%shipdate%</p>
<p><strong>Billing information</strong></p>
<p>%customername%</p>
<p>%customeraddress%</p>
<table>
<tr>
<th style="word-wrap: break-word; text-align: left; width: 120px">Item name</th>
<th style="word-wrap: break-word; text-align: left; width: 140px">Unit price</th>
<th style="word-wrap: break-word; text-align: left; width: 140px">Quantity</th>
<th style="word-wrap: break-word; text-align: left; width: 200px">Total price</th>
</tr>
<tr>
<td style="word-wrap: break-word; text-align: left; width: 120px">%lineproductname%</td>
<td style="word-wrap: break-word; text-align: left; width: 140px">%lineprice%</td>
<td style="word-wrap: break-word; text-align: left; width: 140px">%linequantity%</td>
<td style="word-wrap: break-word; text-align: left; width: 200px">%linenetamount%</td>
</tr>
</table>
</tbody>
</html>
Use the following X++ logic to populate the token map and dispatch the email via SysMailerMessageBuilder:
internal final class SendEmailWithSingleRecord
{
public static void main(Args _args)
{
SendEmailWithSingleRecord::generateEmail();
}
public static void generateEmail()
{
str emailSenderName, emailSenderAddr, emailSubject, emailBody, emailToAddress;
SalesId salesId;
SysEmailId emailId;
SalesTable salesTable;
SalesLine salesLine;
CustTable custTable;
ContactPerson contactPerson;
Map templateTokens;
salesTable = SalesTable::find("000002"); //Sales Id in USMF
salesLine = SalesLine::find(salesTable.salesId);
custTable = CustTable::find(salesTable.CustAccount);
emailToAddress = "Receiver email address";
emailId = "SalesOrdr";
templateTokens = new Map(Types::String, Types::String);
templateTokens.insert("salesid", salesTable.SalesId);
templateTokens.insert("customername", custTable.name());
templateTokens.insert("deliveryaddress", salesTable.deliveryAddress().Address);
templateTokens.insert("customeraddress", custTable.address());
templateTokens.insert("shipdate", strFmt("%1", salesTable.ShippingDateRequested));
templateTokens.insert("lineproductname", salesLine.itemName());
templateTokens.insert("lineprice", strFmt("%1", salesLine.SalesPrice));
templateTokens.insert("linequantity", strFmt("%1", salesLine.SalesQty));
templateTokens.insert("linenetamount", strFmt("%1", salesLine.LineAmount));
if (emailId)
{
[emailSubject, emailBody, emailSenderAddr, emailSenderName] = SendEmailWithSingleRecord::getEmailTemplate(emailId, custTable.languageId());
}
var messageBuilder = new SysMailerMessageBuilder();
messageBuilder.addTo(emailToAddress).setSubject(emailSubject).setBody(SysEmailMessage::stringExpand(emailBody, SysEmailTable::htmlEncodeParameters(templateTokens)));
if (emailSenderAddr)
{
messageBuilder.setFrom(emailSenderAddr, emailSenderName);
SysMailerFactory::getNonInteractiveMailer().sendNonInteractive(messageBuilder.getMessage());
}
}
protected static container getEmailTemplate(SysEmailId _emailId, LanguageId _languageId)
{
var messageTable = SysEmailMessageTable::find(_emailId, _languageId);
var emailTable = SysEmailTable::find(_emailId);
if (!messageTable && emailTable)
{
// Try to find the email message using the default language from the email parameters
messageTable = SysEmailMessageTable::find(_emailId, emailTable.DefaultLanguage);
}
if (messageTable)
{
return [messageTable.Subject, messageTable.Mail, emailTable.SenderAddr, emailTable.SenderName];
}
else
{
warning("@SYS135886"); // Let the user know we didn't find a template
return ['', '', emailTable.SenderAddr, emailTable.SenderName];
}
}
}
Step 4: Dynamic HTML Tables with Multiple Records
When sending notifications with multiple lines (such as sales order items or payment vouchers), define an HTML table container with repeating rows:
<TABLE style="FONT-FAMILY: Calibri; BORDER-COLLAPSE: collapse; TABLE-LAYOUT: fixed; WIDTH: 600px">
<TBODY>
<TR>
<TD style="WORD-WRAP: break-word; TEXT-ALIGN: left; WIDTH: 120px">%empid%</TD>
<TD style="WORD-WRAP: break-word; TEXT-ALIGN: left; WIDTH: 140px">%empname%</TD>
<TD style="WORD-WRAP: break-word; TEXT-ALIGN: left; WIDTH: 140px">%location%</TD>
<TD style="WORD-WRAP: break-word; TEXT-ALIGN: left; WIDTH: 200px">%email%</TD>
</TR>
</TBODY>
</TABLE>
The X++ routine below iterates through transaction records, builds the dynamic HTML table rows in memory, replaces the table token, and dispatches the email:
internal final class SendEmailWithMultipleRecords
{
public static void main(Args _args)
{
SendEmailWithMultipleRecords::generateEmail();
}
public static void generateEmail()
{
str emailSenderName, emailSenderAddr, emailSubject, emailBody, emailToAddress;
SysEmailId emailId;
CustTable custTable;
emailToAddress = "Receiver email address";
emailId = "Employees";
if (emailId)
{
[emailSubject, emailBody, emailSenderAddr, emailSenderName] = SendEmailWithMultipleRecords::getEmailTemplate(emailId, custTable.languageId());
}
var messageBuilder = new SysMailerMessageBuilder();
messageBuilder.addTo(emailToAddress).setSubject(emailSubject).setBody(emailBody);
if (emailSenderAddr)
{
messageBuilder.setFrom(emailSenderAddr, emailSenderName);
SysMailerFactory::getNonInteractiveMailer().sendNonInteractive(messageBuilder.getMessage());
}
}
protected static container getEmailTemplate(SysEmailId _emailId, LanguageId _languageId)
{
str _emailBody;
EmployeeTable employeeTable;
Map templateTokens;
var messageTable = SysEmailMessageTable::find(_emailId, _languageId);
var emailTable = SysEmailTable::find(_emailId);
if (!messageTable && emailTable)
{
// Try to find the email message using the default language from the email parameters
messageTable = SysEmailMessageTable::find(_emailId, emailTable.DefaultLanguage);
}
if (messageTable)
{
templateTokens = new Map(Types::String, Types::String);
// For table header
templateTokens.insert("empid", "Employee ID");
templateTokens.insert("empname", "Employee Name");
templateTokens.insert("location", "Location");
templateTokens.insert("email", "Email Address");
_emailBody = _emailBody + SysEmailMessage::stringExpand(messageTable.Mail , SysEmailTable::htmlEncodeParameters(templateTokens));
while select EmpId, EmployeeName, Location, Email from employeeTable
{
// This will replace variable with actual value
templateTokens.insert("empid", employeeTable.EmpId);
templateTokens.insert("empname", employeeTable.EmployeeName);
templateTokens.insert("location", employeeTable.Location);
templateTokens.insert("email", employeeTable.Email);
// Old body is concatinated with the new body, eg. Table header + first row or all records of the table
_emailBody = _emailBody + SysEmailMessage::stringExpand(messageTable.Mail , SysEmailTable::htmlEncodeParameters(templateTokens));
}
return [messageTable.Subject, _emailBody, emailTable.SenderAddr, emailTable.SenderName];
}
else
{
warning("@SYS135886"); // Let the user know we didn't find a template
return ['', '', emailTable.SenderAddr, emailTable.SenderName];
}
}
}