How to Send Email with Attachments – Simple AL Program in BC

Here you can get a simple Codeunit that can send emails with document attachments by standard email setup on Business CentralAL. You can apply this to your program to send emails with multiple attachments very easily. Here is the Codeunit:

codeunit 50003 "Email Mgt."
{
    var
        TempEmailItem: Record "Email Item" temporary;
        GlobalHideDialog: Boolean;
        GlobalEmailScenario: Enum "Email Scenario";
        GlobalEnqueue: Boolean;

    procedure Send(): Boolean
    var
        OfficeMgt: Codeunit "Office Management";
        EmailScenarioMapping: Codeunit "Email Scenario Mapping";
        Attachments: Codeunit "Temp Blob List";
        Attachment: Codeunit "Temp Blob";
        EmailSentSuccesfully: Boolean;
        IsHandled: Boolean;
        AttachmentStream: Instream;
        AttachmentNames: List of [Text];
        Name: Text[250];
    begin
        TempEmailItem.GetAttachments(Attachments, AttachmentNames);
        if OfficeMgt.AttachAvailable() and (Attachments.Count() > 0) then begin
            Attachments.Get(1, Attachment);
            Attachment.CreateInStream(AttachmentStream);
            OfficeMgt.AttachDocument(AttachmentStream, AttachmentNames.Get(1), TempEmailItem.GetBodyTextFromBlob(), TempEmailItem.Subject);
        end else
            if OfficeMgt.AttachAvailable() then
                OfficeMgt.AttachDocument(TempEmailItem.GetBodyTextFromBlob(), TempEmailItem.Subject);

        if not OfficeMgt.AttachAvailable() then begin
            EmailSentSuccesfully := TempEmailItem.Send(GlobalHideDialog, GlobalEmailScenario, GlobalEnqueue);
            exit(EmailSentSuccesfully);
        end;
    end;

    procedure InitEmail(Body: Text; Subject: Text; MailTo: Text; HideDialog: Boolean): Boolean
    begin
        Clear(TempEmailItem);
        TempEmailItem.Validate("Plaintext Formatted", true);
        TempEmailItem.SetBodyText(Body);
        TempEmailItem."Send to" := CopyStr(MailTo, 1, MaxStrLen(TempEmailItem."Send to"));
        TempEmailItem.Subject := CopyStr(Subject, 1, MaxStrLen(TempEmailItem.Subject));
        GlobalHideDialog := HideDialog;
        GlobalEmailScenario := Enum::"Email Scenario"::Default;
        GlobalEnqueue := false;
    end;

    procedure AddAttachment(AttachmentStream: InStream; AttachmentName: Text)
    begin
        TempEmailItem.AddAttachment(AttachmentStream, AttachmentName);
    end;

    procedure AddAttachment(DocumentAttachment: Record "Document Attachment")
    var
        AttachmentStream: InStream;
        TenantMedia: Record "Tenant Media";
    begin
        if not TenantMedia.get(DocumentAttachment."Document Reference ID".MediaId) then
            exit;
        TenantMedia.CalcFields(Content);
        if not TenantMedia.Content.HasValue then
            exit;
        Clear(AttachmentStream);
        TenantMedia.Content.CreateInStream(AttachmentStream);
        AddAttachment(AttachmentStream, StrSubstNo('%1.%2', DocumentAttachment."File Name", DocumentAttachment."File Extension"));
    end;

    procedure AddAttachments(var DocumentAttachment: Record "Document Attachment")
    begin
        if not DocumentAttachment.FindSet() then
            exit;
        repeat
            AddAttachment(DocumentAttachment);
        until DocumentAttachment.Next() = 0;
    end;
}Code language: JavaScript (javascript)

Test 1: Send email including attachments from Document Attachment with Mail Dialog

The following test code example will show how to send emails including attachments from the “Document Attachment” table in Business Central.

procedure TestSendMailWithDocumentAttachments()
    var
        EMailMgt: Codeunit "Email Mgt.";
        DocumentAttachment: Record "Document Attachment";
        BodyText, Subject, Email : Text;
    begin
        BodyText := 'Dear Sir,<br> <p>This is a <b>test email with document attachments</b>.</p> <hr> tested by <b>NAVUSER</B> <hr><br> Thank You!'; //HTML body
        Subject := 'Test Email - Attchments by Document Attachment';
        Email := '[email protected]';

        EMailMgt.InitEmail(BodyText, Subject, Email, false); //Init email with showing mail dialog by passing last parameter as false

        //Filter Document Attchment for customer: 01121212
        DocumentAttachment.SetRange("Table ID", Database::Customer);
        DocumentAttachment.SetRange("No.", '01121212');

        EMailMgt.AddAttachments(DocumentAttachment);  //Add attachments by the filterd "Document Attachment" table

        //Send Email
        if EMailMgt.Send() then
            Message('Email has been sent.');
    end;Code language: PHP (php)

After executing the above test code mail popup dialog will be shown as per the below:

How to send email including attachments from Document Attachment with Mail Dialog in BC AL

As per the test code attachments also attached from the customer (‘01121212’) document attachment:

Test 2: Send email including attachments from Input Stream with Mail Dialog

The following test code example will show how to send emails including attachments from an input stream.

procedure TestSendMailWithAttachmentsByInsStream()
    var
        EMailMgt: Codeunit "Email Mgt.";
        BodyText, Subject, Email : Text;
        InStream: InStream;
        FileName: text;
    begin
        BodyText := 'Dear Sir,<br> <p>This is a <b>test email with uploading attachments by input stream</b>.</p> <hr> tested by <b>NAVUSER</B> <hr><br> Thank You!'; //HTML body
        Subject := 'Test Email - Attchments by Input Stream';
        Email := '[email protected]';

        EMailMgt.InitEmail(BodyText, Subject, Email, false); //Init email with showing mail dialog by passing last parameter as false

        //Test Upload attachment 1
        UploadIntoStream('Add Attachment 1', '', '', FileName, InStream);
        EMailMgt.AddAttachment(InStream, FileName);  //Add attachments by input stream

        //Test Upload attachment 2
        Clear(InStream);
        UploadIntoStream('Add Attachment 2', '', '', FileName, InStream);
        EMailMgt.AddAttachment(InStream, FileName);  //Add attachments by inpur stream

        //You can add more attachments as you want

        //Send Email
        if EMailMgt.Send() then
            Message('Email has been sent.');
    end;Code language: PHP (php)

After executing the above test code mail popup dialog will be shown as per the below:

How to send email including attachments from Input Stream with Mail Dialog on Business Central - AL

Test 3: Send email without Mail Dialog (Directly)

You also can send email directly without opening the mail dialog window. It is very simple, and the only change is to pass the “true” value for the parameter: “HideDialog” in the “InitEmail” function:

EMailMgt.InitEmail(BodyText, Subject, Email, true);Code language: JavaScript (javascript)

Here is the example:

How to send email without Mail Dialog (Directly) in BC AL

Tested Mail output:

How to send email with attached documents directly and with mail dialog window by standard BC email setup AL

Visit the previous guide about how to create a custom REST API in Business Central.

Senior Solutions Architect - Microsoft Dynamics Navision / Microsoft Dynamics 365 Business Central and freelance developer. (The admin of NAVUSER)

Leave a Comment