Skip to main content

Email Processing - Distributor Batch


Often we need to send emails during a process in Dynamics 365 for Finance and Operations. That's quite a standard requirement which often makes you look up some examples of your own or web.


Here is yet another blog post on email sending. 


In this blog post I will provide a few examples of sending email. But first let me introduce you some terms.


  • Email template - Templates stored underOrganization administration>Setup>Organization email templates. The underlying tables are SysEmailTable and SysEmailMessageTable.
  • Placeholder - a string enclosed within percent (%) symbols. E.g. %placeholder%.
  • Email processing table - two tables SysOutgoingEmailTable and SysOutgoingEmailData that store emails to be processed by a batch job. Emails can be found under System administration>Periodic tasks>Email processing>Email sending status.

I assume you have all you email parameters in place and its functional.

Let's send some emails! 

The simplest way is to send it directly. Check out the following example:

var builder = new SysMailerMessageBuilder();

builder.addTo("receiver@test.com");
builder.setFrom("sender@test.com");

builder.setSubject("The greatest email of all time");
builder.setBody("This is the best email ever. I believe in code!");
var message = builder.getMessage();

SysMailerFactory::getNonInteractiveMailer().sendNonInteractive(message);

TipaddTo method accepts semicolon separated email addresses.

Let's be a little bit more sophisticated and create an email template.
image

Now let's send an email using the template.


SysEmailTable        sysEmailTable        = SysEmailTable::find('MyTemplate');
SysEmailMessageTable sysEmailMessageTable = SysEmailMessageTable::find(sysEmailTable.EmailId, sysEmailTable.DefaultLanguage);

var builder = new SysMailerMessageBuilder();

builder.addTo("receiver@test.com");
builder.setFrom(sysEmailTable.SenderAddr, sysEmailTable.SenderName);

builder.setSubject(sysEmailMessageTable.Subject);
builder.setBody(sysEmailMessageTable.Mail);
var message = builder.getMessage();

SysMailerFactory::getNonInteractiveMailer().sendNonInteractive(message);

What's the template without placeholders, right?

Let's add a couple of placeholders %UserName% and %DateTime% and resolve them. But first we need to add them to the template.


image


See the code example bellow on how to resolve the placeholders:


SysEmailTable        sysEmailTable        = SysEmailTable::find('MyTemplate');
SysEmailMessageTable sysEmailMessageTable = SysEmailMessageTable::find(sysEmailTable.EmailId, sysEmailTable.DefaultLanguage);

str messageBody = sysEmailMessageTable.Mail;
str subject = sysEmailMessageTable.Subject;

Map placeholderMap = new Map(Types::String, Types::String);

placeholderMap.insert("UserName", "Evaldas Landauskas");
placeholderMap.insert("DateTime", strFmt("%1", DateTimeUtil::getSystemDateTime()));

messageBody = SysEmailMessage::stringExpand(messageBody, placeholderMap);
subject = SysEmailMessage::stringExpand(subject, placeholderMap);

var builder = new SysMailerMessageBuilder();

builder.addTo("receiver@test.com");
builder.setFrom(sysEmailTable.SenderAddr, sysEmailTable.SenderName);

builder.setSubject(subject);
builder.setBody(messageBody);
var message = builder.getMessage();

SysMailerFactory::getNonInteractiveMailer().sendNonInteractive(message);

Note: Keys in the map are not enclosed with %, the code inside stringExpand encloses the keys.

image


OK. Let's try one more thing. Let's say you would like to have a control on emails, like being able to resend in case of some failure.

In this example we will use email processing table instead of directly sending an email. 


SysEmailTable        sysEmailTable        = SysEmailTable::find('MyTemplate');
SysEmailMessageTable sysEmailMessageTable = SysEmailMessageTable::find(sysEmailTable.EmailId, sysEmailTable.DefaultLanguage);

str messageBody = sysEmailMessageTable.Mail;
str subject = sysEmailMessageTable.Subject;

Map placeholderMap = new Map(Types::String, Types::String);

placeholderMap.insert("UserName", "Evaldas Landauskas");
placeholderMap.insert("DateTime", strFmt("%1", DateTimeUtil::getSystemDateTime()));

messageBody = SysEmailMessage::stringExpand(messageBody, placeholderMap);
subject = SysEmailMessage::stringExpand(subject, placeholderMap);

SysOutgoingEmailTable outgoingEmailTable;
SysOutgoingEmailData outgoingEmailData;

outgoingEmailTable.EmailItemId = EventInbox::nextEventId();
outgoingEmailTable.TemplateId = sysEmailTable.EmailId;
outgoingEmailTable.Sender = sysEmailTable.SenderAddr;
outgoingEmailTable.SenderName = sysEmailTable.SenderName;
outgoingEmailTable.Recipient = 'receiver@test.com';
outgoingEmailTable.Subject = subject;
outgoingEmailTable.Message = messageBody;
outgoingEmailTable.Priority = sysEmailTable.Priority;
outgoingEmailTable.WithRetries = true;
outgoingEmailTable.RetryNum = 0;
outgoingEmailTable.UserId = curuserid();
outgoingEmailTable.Status = SysEmailStatus::Unsent;
outgoingEmailTable.LatestStatusChangeDateTime = DateTimeUtil::getSystemDateTime();
outgoingEmailTable.insert();

And the result is this.

image

The emails in this table are processed via batch job
System administration>Periodic tasks>Email processing>Email distributor batch.

Comments

Popular posts from this blog

EXCEL Add-in D365 FO

EXCEL add-in USED FOR D365 DATA ENTITY To use excel add-in for D365 data entities for CRUD operations. You can easily follow below mentioned steps: 1. Open Excel from any Desktop or VM and click on Add-ins option under insert tab: 2. Check if you have Microsoft Dynamics Office Add-ins, If not then download it from Microsoft store: 3. If you have above mentioned Add-in click on this and click add server information: 4. In server URL add your environment URL either dev, UAT or PROD and click OK.  for e.g:  (https://xxxxxxxxxxxxxxxxxxx.dynamics.com/)  5. Click on Design button and it will display below mentioned screen: 6. Click on Select entity data source and choose your desired data entity from list on which you need to perform CRUD operations and click on NEXT: 7. Double click on each field present in AVAILABLE FIELD SECTION to get them in SELECTED FIELD SECTION: 8. Click on Refresh Once and you will be able to see data in your entity in Excel: 9. After making changes to...

Deep Links

  DEEP LINKS FOR SALES ORDERS In this blog we will discuss about generating deep links for any form , record or datasource. Deep links are basically termed for generating URL's through code for any specific record in D365. Using Deep links other environments can access D365 records by using this URL generated from it. 1. In below blog I am creating Deep links for sales order header record. 2. To Access these links one should always be added the user in FinOps to access through URL. Step #1 Create and extension class of  URLUtility class  and also add following code snippet to access this class : using Microsoft.Dynamics.AX.Framework.Utilities; using Microsoft.Dynamics.@Client.ServerForm.Contexts; public static str generateRecordUrl(str _menuItemName, MenuItemType _menuItemType, DataSourceName _dataSourceName, Map _indexFieldValuesMap, DataAreaId _dataAreaId = curExt()) {   System.Uri host = SessionContext::Get_Current().Get_RequestUrl();   UrlHelper.UrlGenerator...

Record level Security Ax 2012

RECORD LEVEL SECURITY IN AX 2012 In this blog we will discuss record level security in Ax 2012. Record level security includes Query, Constrained table, Security policy, Temp table (Optional).   Create a query That will be used to restrict data access from the  Constraint  table. Right-click  Data Sources , and the select  New Data Source . In the  Table  field, enter the primary table name  CustGroup . Right-click  Ranges , and then select  New Range . Set the  Enabled  field to  Yes . In the  Data Source  field, enter the primary table name, in this case, ‘CustGroup’. In the  Value field , enter  10  to restrict access to data where CustGroup has value of 10, by defining the Range for the CustGroup field. Add a new security policy Add a new security policy.  Set  Constrained Table  to  Yes . This will also secure access to the primary table. In this example this is the...