web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Small and medium business | Business Central, N...
Unanswered

Add Multiple Attachments to Email

(0) ShareShare
ReportReport
Posted on by 629

Hi, 
I needed to update my code to add multiple attachments to an Email.(In my case from Purchase Order). Here's my procedure to add multiple attachments. 
Replace "SMTP Mail" and "SMTP Mail Setup" with the Codeunits "Email" and "Email Message".

pastedimage1649095975745v1.png


     
PROCEDURE ReportSendMailWithExternalAttachment(
    ReportToSend: Integer;
    Recordr: RecordRef;
    TableID: Integer;
    DocNo: Text;
    ToAddr: List of [Text];
    Subject: Text[100];
    Body: Text[200];
    AttachmentName: Text[100];
    Param: Text; var Purchaseheader: Record "Purchase Header"): Boolean
    var
        TempBlob: Codeunit "Temp Blob";
        outStreamReport: OutStream;
        inStreamReport: InStream;
        TempBlobAtc: Array[10] of Codeunit "Temp Blob";
        outStreamReportAtc: Array[10] of OutStream;
        inStreamReportAtc: Array[10] of InStream;
        Parameters: Text;
        EmailObj: Codeunit Email;
        EmailMsg: Codeunit "Email Message";
        Question: Label 'Are you Sure you want to send an email to %1';
        SendYesNo: Boolean;
        // Attachments
        FullFileName: Text;
        DocumentAttachment: record "Document Attachment";
        i: Integer;

    begin
        EmailMsg.Create(ToAddr, Subject, Body, false);
        //Generate blob from report
        TempBlob.CreateOutStream(outStreamReport);
        TempBlob.CreateInStream(inStreamReport);
        Report.SaveAs(ReportToSend, Param, ReportFormat::Pdf, outStreamReport, Recordr);
        // Mail.AddAttachmentStream(inStreamReport, AttachmentName);
        i := 1;

        //Get attachment from the document - streams
        DocumentAttachment.Reset();
        DocumentAttachment.setrange("Table ID", TableID);
        DocumentAttachment.setrange("No.", DocNo);
        if DocumentAttachment.FindSet() then begin
            repeat
                if DocumentAttachment."Document Reference ID".HasValue then begin
                    TempBlobAtc[i].CreateOutStream(outStreamReportAtc[i]);
                    TempBlobAtc[i].CreateInStream(inStreamReportAtc[i]);
                    FullFileName := DocumentAttachment."File Name" + '.' + DocumentAttachment."File Extension";
                    if DocumentAttachment."Document Reference ID".ExportStream(outStreamReportAtc[i]) then begin
                        //Mail Attachments
                        EmailMsg.AddAttachment(FullFileName, 'PDF,', inStreamReportAtc[i]);
                    end;
                    i += 1;
                end;
            until DocumentAttachment.NEXT = 0;
        end;

        //Send mail
exit(EmailObj.Send(EmailMsg));
    end;
I have the same question (0)
  • David Wyke Profile Picture
    126 on at

    Hi Hein, I'm not sure about updating this based on your code (I tend to stick more to functionality than development, my AL is a little shaky!), but there is an "off-the-shelf" product available in appsource that caters for this requirement, Continia Document Output.

    Continia Document Output allows you to create dynamic email templates that populate emails sent to vendors and customers (Purch. Orders, Quotes, Sales equivalent, Remits, Statements etc.) that update with document numbers, recipient name(s), allow for sending to multiple recipients based on rules set against the customer / vendor record, and importantly for you, to include any attachments added to the documents factbox i.e. if a document was attached (PDF, Excel etc.) to a Purchase Order and you send the PO to the Vendor it can also automatically include the supporting document and can merge it into the PO pdf. 

    It's a great tool and one I regularly implement on projects.

  • Lakshmanan.R Profile Picture
    137 on at

    Hi Hein Kruger,

    Have you achieved in meeting out your requirement ? If so, Please do share me your steps in achieving it. 

    Thanks & Regards,

    Lakshmanan R

  • Hein Kruger Profile Picture
    629 on at

    Hi Lakshmanan,

    Here is an example of how I used the ReportSendMailWithExternalAttachment() in a Code Unit that runs with a JobQueue once a day.

    The Code sends the Sales Order Report to multiple emails. The Emails are stored in the Table "Distribution Email List". You can Replace this with one email address.

    //***************************************//

    trigger OnRun()

       var

           TodaySalesOrder: Report "Today Sales";

           SalesHeader: Record "Sales Header";

           DistributionEmailList: Record "Distribution Email List";

           param: Text;

           Body: Text;

       begin

           //Get all the Active users from the Distribution Email list

           DistributionEmailList.Reset();

           DistributionEmailList.SetRange("Active User", True);

           if DistributionEmailList.FindSet() then

               repeat

                   SalesHeader.Reset();

                   SalesHeader.SetRange("Document Date", System.Today, CalcDate('<+1D>', System.Today));

                   SalesHeader.SetRange("Document Type", SalesHeader."Document Type"::Order);

                   if SalesHeader.FindSet() then begin

                       Body := EmailBody(DistributionEmailList."User Name");

                       RecRef.GetTable(SalesHeader);

                       TodaySalesOrder.SetTableView(SalesHeader);

                       TodaySalesOrder.UseRequestPage := false;

                       param := ParamterOne;

                       ReportSendMailWithExternalAttachment(Report::"Today Sales", RecRef, RecRef.Number, DistributionEmailList."User Email", 'Today Deliveries', Body, StrSubstNo('%1', System.Today) + '_Deliveries.pdf', param, SalesHeader);

                       Clear(TodaySalesOrder);

                   end;

               until DistributionEmailList.Next() = 0;

       end;

       local procedure EmailBody(var UserName: Text[25]): Text

       var

           BodyLbl: Label 'Dear %1,<br><br> Please find the Sales Deliveries for %2..%3 attached. <br><br> P.S This is an automated email. Please do not respond. <br><br> Regards, <br><br> Management';

           ExitText: Text;

       begin

           Clear(ExitText);

           ExitText := StrSubstNo(BodyLbl, UserName, System.Today(), CalcDate('<+1D>', System.Today));

           exit(ExitText);

       end;

    //*****************************************//

    This will

  • Lakshmanan.R Profile Picture
    137 on at

    Dear Hein Kruger,

    Thanks for you response.

    Actually, I are looking on how to send two attachments (i.e. two reports) on a single email. Can you please suggest me the ways in meeting out my requirement..?

    Thanks in advance,

    Lakshmanan R

  • Nitin Verma Profile Picture
    21,708 Moderator on at

    Hi,

    Please refer the below link

    robertostefanettinavblog.com/.../

  • Hein Kruger Profile Picture
    629 on at

    I used  Roberts code as my initial start point.

    The email codeunits are deprecated from BC 20.

    See in the comments of robertostefanettinavblog.com/.../  I have added the same code as above.

  • Lakshmanan.R Profile Picture
    137 on at

    Dear Nitin Verma,

    Thanks a lot for your response. I had tried this one out, but I am not able to achieve this..

    Is there any other way that would help me in meeting my requirement.?

    Thanks & Regards,

    Lakshmanan R

  • Lakshmanan.R Profile Picture
    137 on at

    Dear Hein Kruger,

    Can you please share the updated code(final code)..?

    Thanks in advance,

    Lakshmanan R

  • Hein Kruger Profile Picture
    629 on at

    Hi Lakshmanan,

    This is  my update code (Final Code) in the thread.

    Create a CodeUnit and Copy and Paste the code in.

    There are three Procedures.

    * OnRun()

    * ReportSendMailWithExternalAttachment()

    *EmailBody()

    If you have all of them, you should be good to go. You can run the CodeUnit from Job Queues.

    Please indicate where you are getting errors.

  • Nitin Verma Profile Picture
    21,708 Moderator on at

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Small and medium business | Business Central, NAV, RMS

#1
OussamaSabbouh Profile Picture

OussamaSabbouh 2,917

#2
Jainam M. Kothari Profile Picture

Jainam M. Kothari 1,161 Super User 2025 Season 2

#3
YUN ZHU Profile Picture

YUN ZHU 1,025 Super User 2025 Season 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans