Developing with the new enhanced email feature

Enhanced Email Feature

Yesterday, I had an email notification about a new blog post from my colleague Josh Anglesea. A great post on the new enhanced email feature coming with Business Central v17. Out of pure coincidence, I happened to be looking into the same functionality, but from a development perspective… So inspired by Josh here’s a blog post about developing with the new enhanced email feature.

Josh already did a great job explaining how to setup the new functionality, so I highly recommend you read his post before continuing as I won’t go into this.

The major change this new enhanced email functionality offers is the ability to configure multiple email accounts and have Business Central select the correct account based on the scenario. This is in contrast to the single account you can configure per Business Central company using the old SMTP Setup page.

This brings us to the first new concept: Email Scenario

When you create a new email account, you can choose which scenarios this account will be used in. The scenarios offered by the base application are defined in an enumextension object, which extends the systems app’s Email Scenario Enum:

enumextension 8891 "Base Email Scenario" extends "Email Scenario"
{
   value(1; "Invite External Accountant")
   {
       Caption = 'Invite External Accountant';
   }
   value(2; "Notification")
   {
       Caption = 'Notification';
   }
   value(3; "Job Planning Line Calendar")
   {
       Caption = 'Job Planning Line Calendar';
    }

    // Document usage

    // ------------------------------------------------------------------------------------------------

   value(100; "Sales Quote")
   {
       Caption = 'Sales Quote';
   }
   value(101; "Sales Order")
   {
       Caption = 'Sales Order';
   }
   value(102; "Sales Invoice")
   {
       Caption = 'Sales Invoice';
   }
   value(103; "Sales Credit Memo")
   {
       Caption = 'Sales Credit Memo';
   }
   value(105; "Purchase Quote")
   {
       Caption = 'Purchase Quote';
   }
   value(106; "Purchase Order")
   {
       Caption = 'Purchase Order';
   }
   value(115; "Reminder")
   {
       Caption = 'Reminder';
   }
   value(116; "Finance Charge")
   {
       Caption = 'Finance Charge';
   }
   value(129; "Service Quote")
   {
       Caption = 'Service Quote';
   }
   value(130; "Service Order")
   {
       Caption = 'Service Order';
   }
   value(131; "Service Invoice")
   {
       Caption = 'Service Invoice';
   }
   value(132; "Service Credit Memo")
   {
       Caption = 'Service Credit Memo';
   }
   value(184; "Posted Vendor Remittance")
   {
       Caption = 'Posted Vendor Remittance';
   }
   value(185; "Customer Statement")
   {
       Caption = 'Customer Statement';
   }
   value(186; "Vendor Remittance")
   {
       Caption = 'Vendor Remittance';
   }
}



Building your own functionality on top of this, you’ll probably want to add to the list of scenarios. Good news! This is as simple as extending the Email Scenario Enum in our own apps:

enumextension 50100 "Dan Test Email Scenario DDK" extends "Email Scenario"
{
   value(50100; "Dan Test 1 DDK")
   {
       Caption = 'Dan Test 1';
   }
   value(50101; "Dan Test 2 DDK")
   {
       Caption = 'Dan Test 2';
   }
}


Once you’ve created your enumextension, the new options are automatically included in the Email Scenario list:

Email Scenario

Next up, we need to create an email message and send. This is done using the Email Message and Email Codeunits.

Note: The enhanced email app is part of the system app, so you won’t be able to see the source code from VS Code, or by extracting the base application app file. The system application apps are open source and available on GitHub to view and submit your own changes, the email app can be found here: https://github.com/microsoft/ALAppExtensions/tree/master/Modules/System/Email


The following example show how you can create an email message and send using the email scenario functionality:

    procedure SendEmail()
   var
       Email: Codeunit Email;
       EmailMessage: Codeunit "Email Message";
   begin
       EmailMessage.Create('dan@dankinsella.blog', 'My Subject', 'My message body text');
       Email.Send(EmailMessage, Enum::"Email Scenario"::"Dan Test 1 DDK");
    end;

As you can see, we can pass the email scenario into the send procedure. If an account is associated with this scenario it will be selected for use. If no account is assigned to this scenario the default account will be used.

Note the Email.Send() procedure is overloaded, meaning it can take different sets of parameters, so have a look at the object here for all the available options.

Some other cool stuff to check out:

You can open the new email editor using Email.OpenInEditor() to allow your users to edit the email before sending:

 /// <summary>
/// Opens an email message in "Email Editor" page.
/// </summary>
/// <param name="EmailMessage">The email message to use as payload.</param>
/// <param name="EmailScenario">The scenario to use in order to determine the email account to use on the page.</param>
procedure OpenInEditor(EmailMessage: Codeunit "Email Message"; EmailScenario: Enum "Email Scenario")
begin
EmailImpl.OpenInEditor(EmailMessage, EmailScenario, false);
end;

We can also send the email in the background by putting it on the scheduler using Enqueue procedure:

 /// <summary>
/// Enqueues an email to be sent in the background.
/// </summary>
/// <param name="EmailMessage">The email message to use as payload.</param>
/// <param name="EmailScenario">The scenario to use in order to determine the email account to use for sending the email.</param>
procedure Enqueue(EmailMessage: Codeunit "Email Message"; EmailScenario: Enum "Email Scenario")
begin
EmailImpl.Enqueue(EmailMessage, EmailScenario);
end;

Attachments can be added to the email message using an InStream, something like this:

    procedure SendEmailWithAttachment(AttachmentTempBlob: Codeunit "Temp Blob")
   var
       Email: Codeunit Email;
       EmailMessage: Codeunit "Email Message";
       AttachmentInStream: InStream;
   begin
       EmailMessage.Create('dan@dankinsella.blog', 'My Subject', 'My message body text');
       AttachmentTempBlob.CreateInStream(AttachmentInStream);
       EmailMessage.AddAttachment('My Attachment name', 'PDF', AttachmentInStream);
       Email.Send(EmailMessage, Enum::"Email Scenario"::"Dan Test 2 DDK");
   end;

16 thoughts on “Developing with the new enhanced email feature”

  1. How do you add line feed into email body? do you have to add chr(13)?

    Also how about hyperlinks to BC documents? I have the URL, but how to make it a hyperlink, like in the Notification Email report 1320? Thx.

    1. Hi Geoff, yes you can add CRLF characters to text manually or you can use the WriteText() procedure when streaming your text into a blob. If you want to add links and have better layout control of the email body then I’d suggest using HTML as the email body. There is a parameter to indicate the body is HTML which will set the content type so email clients render it correctly.

  2. Hello,

    do you by chance know what you have to do with these new features when you want to add a BCC email address? I’ve been researching on-and-of for more than 2 weeks but can’t seem to find anything.

    Can this also be somehow done with the email scenario?

    1. Hey Sabine, yes one of the create() procedures on the Email Message codeunit has a parameter called BCCRecipients. It’s a list of text you’ll need to populate with bcc email addresses

    2. CC & BCC is available globally. Check page 2128.
      If you need it to be more specific , you can do some customization. I think you can achieve this by simply code in event ‘OnBeforeSendEmail’ in Codeunit::”Document-Mailing”.

      TempEmailItem.”Send CC” := ‘someemail1@google.com’;

      BC will process the TempEmailItem when sending.
      Hope it helps.

  3. We are facing this error “Cannot authenticate the credentials on server smtp.office365.com” in the email outbox while sending email using email, and email message codeunit. We get the same error when we send the test email using email setup as well. But whenever we send using using smtp setup or smtp codeunit then we receive the email successfully.

    1. I also have this problem and I believe it stems from the fact that process is not finding your Email Account records which no doubt have Connection=SMTP. My process is only looking for Connection=Current User. Struggling to fathom why that is, as the code passes into one of non-base/non-system extensions and i cannot see the code it is executing.

      1. Hi Jon, did you ever figure this out? We’re having the same issue when sending. It’s using the extension name as the sender and failing.

  4. Hi, I’m new in BC development and I want to know if it is possible to attach an Excel file. For example, I have to fill an Excel with all the customer in the Customer table and send it by email. I use “Excel Buffer” for the creation of the file, is it possible to directly add this Excel to the Email without having to download it ?

  5. i am facing issues with Attachment code can you help me on please explain in details

    EmailMessage.AddAttachment(‘My Attachment name’, ‘PDF’, AttachmentInStream);

  6. Hello thank you very much.
    Question, is any additional configuration required in business central so that files can be attached and so that the html tags within the code identify me?

    1. In EmailMsg.Create() function, last parameter is for HTMLFormatted so you need to keep that true and it will start identifying your html tags.

  7. Hi, Can we tag Email accounts to the users. Actually there are multiple users that works on both sales and purchase documents, now I want to use the different “from email id” for the different Login. IS it possible

  8. Hi,

    We have a requirement to send email to more than 10 emails in one go for Customer Statement.
    In document layout, the maximum char for field ‘Send to Email’ is 200 chars which is not enough.

    The idea is to add ‘Send to Email 2’ and add the recipient emails when system is sending the email.

    The nearest event before sending is ‘OnSendViaEmailModuleOnAfterCreateMessage’ in Codeunit::”Mail Management”.
    As the example above, we can add ToList or CCList when creating message. However in this case, Message is already created by system, and unfortunately, Email Message codeunit do not provide function to add more recipient. Only some getrecipient and addattachment functions is available .

    Any idea, how to achieve the objective (send to 10 or 20 emails in one go ) ?

    Many thanks

  9. I understand the ‘From Address’ is read from the email account, but what if you want to override that? Can the From Address be set in code?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.