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...
Answered

Error while sending email with attachment on custom page

(0) ShareShare
ReportReport
Posted on by 13

Hi

I am getting the, following error while I am sending a bulk email  with attachments (PDF),  it is giving  an error

ERROR

-----------

The Tenant Media does not exist. Identification fields and values: ID='{00000000-0000-0000-0000-000000000000}'

My code 

----------

codeunit 50100 "BGS_Follow Email pattern"
{
    Trigger OnRun()
    begin
       // SendSalesShipment()
    end;

    var
        TempEmailItem: Record "Email Item" temporary;
        Rep50000: Report "BGS_Price Email Send -MMBS";
        Rep50001: Report "BGS_Price Email Send-Bulk";
        etxt: Label ';';
        Filename: text;
        Kout: InStream;

    local procedure "--Version--2.0--"()
    begin
    end;

    procedure SendSalesShipment(mailRec: Record "BGS_Email Notices"; OrderNo: Code[20]; CustNo: Code[20]; srundate: Date): Boolean
    var
        Customer: Record Customer;
        EmailBodyFilePath: Text;
        //FileManagement: Codeunit "File Management";
        ReportID: Integer;
        BodyLayoutCode: Code[20];
        emailrec: Record "BGS_Email Notices";
        fromDt: Date;
        todt: Date;
        Email: Codeunit Email;
        EmailMessage: Codeunit "Email Message";
        AttachmentInStream: InStream;
        AttachmentInStream1: InStream;
        OutStr: OutStream;
        AttachmentTempBlob: Codeunit "Temp Blob";
        "Send to": Code[50];
        "Send CC": Code[50];
        Subject: text[250];
        ReadTextChk_lTxt: Text;
    begin

        if not Customer.Get(mailRec."Customer No") then
            exit;
        if Customer."E-Mail" = '' then
            exit;

        //with TempEmailItem do begin
        "Send to" := Customer."E-Mail";
        "Send CC" := Customer."CC Email" + etxt + Customer."CC Email 2";
        Subject := StrSubstNo('Monthly Price Revision %1', mailRec."Customer No");
        fromDt := CalcDate('<-1M>', mailRec."Price Date");
        fromDt := CalcDate('-CM', CalcDate('<-1M>', mailRec."Price Date"));
        emailrec.Reset;
        emailrec.SetFilter("Customer No", mailRec."Customer No");
        emailrec.SetFilter("Order No", mailRec."Order No");
        emailrec.SetRange("Price Date", fromDt, mailRec."Price Date");

        // Getting Report Layout
        //----------------------
        GetReportIDandLayoutCode(ReportID, BodyLayoutCode, emailrec);
        Filename := StrSubstNo('Monthly Price Note %1', mailRec."Customer No" + '.PDF');
       
        //Passing Argument to Reports
        //--------------------------
        Clear(Rep50000);
        Rep50000.GetArgs(mailRec."Customer No", OrderNo, fromDt, srundate, '');
        // Email Body
        //------------------
        if emailrec.Segment = 'BULK' then
            GenerateShipmentEmailBody(emailrec, 50100, EmailBodyFilePath, BodyLayoutCode, OrderNo, CustNo, srundate)
        else
            GenerateShipmentEmailBody(emailrec, 50101, EmailBodyFilePath, BodyLayoutCode, OrderNo, CustNo, srundate);

        EmailMessage.Create("Send to", Subject, 'Price Notification');
        AttachmentTempBlob.CreateInStream(AttachmentInStream);
        EmailMessage.AddAttachment(CustNo, 'PDF', AttachmentInStream);
        //Nilesh Suggestion while sending email
        AttachmentInStream1.ReadText(ReadTextChk_lTxt);
        IF ReadTextChk_lTxt <> '' THen
            EmailMessage.AddAttachment(CustNo, 'PDF', AttachmentInStream1);
        Email.Send(EmailMessage, Enum::"Email Scenario"::"Gas Price Email");

        // // Getting Email Body
        // //-------------------
        // if emailrec.Segment = 'BULK' then
        //     GenerateShipmentEmailBody(emailrec, 50100, EmailBodyFilePath, BodyLayoutCode, OrderNo, CustNo, srundate)
        // else
        //     GenerateShipmentEmailBody(emailrec, 50101, EmailBodyFilePath, BodyLayoutCode, OrderNo, CustNo, srundate);
    end;
    //kmk new replacment code
    //---------------
    local procedure GenerateShipmentEmailBody(DocumentVariant: Record "BGS_Email Notices"; ReportID: Integer; var BodyFilePath: Text; LayoutCode: Code[20]; Korderno: Code[20]; Kcustno: Code[20]; Krundate: Date)
    var

        //  FileManagement: Codeunit "File Management";
        ReportLayoutSelection: Record "Report Layout Selection";
        bemailrec: Record "BGS_Email Notices";
        //---
        TempBlob_lRec: Codeunit "Temp Blob";

        //---------------
        Out: OutStream;
        RecRef: RecordRef;
        //-----------
        TempBlob: Codeunit "Temp Blob";
        OutStr: OutStream;
        InStrm: InStream;
        // RecRef : RecordRef;
        Base64EncodedString: Text;
        Base64: Codeunit "Base64 Convert";
        //--------------
        bfromDt: Date;
        btodt: Date;
    begin
        // BodyFilePath := CopyStr(FileManagement.ServerTempFileName('html'), 1, 250);
        ReportLayoutSelection.SetTempLayoutSelected(LayoutCode);

        bfromDt := CalcDate('<-1M>', Krundate);
        Clear(Rep50000);
        Rep50000.GetArgs(Kcustno, Korderno, bfromDt, Krundate, '');
        bemailrec.Reset;
        bemailrec.SetFilter("Customer No", Kcustno);
        bemailrec.SetFilter("Order No", Korderno);
        bemailrec.SetRange("Price Date", bfromDt, Krundate);
        RecRef.GetTable(bemailrec);
        // -----
        TempBlob.CreateOutStream(OutStr);
        // ----
        if bemailrec.Segment = 'BULK' then
            REPORT.SAVEAS(50101, '', REPORTFORMAT::Pdf, Out, RecRef)

        ELSE    // save report in TempBlob di recRef
            REPORT.SAVEAS(50100, '', REPORTFORMAT::Pdf, Out, RecRef);                                                              // FileManagement_lCdu.BLOBExport(TempBlob_lRec, STRSUBSTNO('Proforma_%1.Pdf', bemailrec."Customer No"), TRUE);   // export report in PDF format
        TempBlob.CreateInStream(InStrm);
        //REPORT.SaveAsHtml(ReportID, BodyFilePath, bemailrec);
        ReportLayoutSelection.SetTempLayoutSelected('');
    end;

    local procedure GenerateDocumentEmailAttachment(DocumentVariant: Record "BGS_Email Notices"; ReportID: Integer; zdate: Date; zorder: Code[20]; zcust: Code[20]): Text
    var
        // FileManagement: Codeunit "File Management";
        FilePath: Text;

        Zemailrec: Record "BGS_Email Notices";
        zfromDt: Date;
        Out: OutStream;
        RecRef: RecordRef;
        //-----------
        TempBlob: Codeunit "Temp Blob";
        OutStr: OutStream;
        InStrm: InStream;
        // RecRef : RecordRef;
        Base64EncodedString: Text;
        Base64: Codeunit "Base64 Convert";
        //--test---
        Instr2_Chk: InStream;
    //-------
    //-----------
    begin
        zfromDt := CalcDate('<-1M>', zdate);
        Zemailrec.Reset;
        Zemailrec.SetFilter("Customer No", zcust);
        Zemailrec.SetFilter("Order No", zorder);
        Zemailrec.SetRange("Price Date", zfromDt, zdate);
        Zemailrec.findfirst;
        RecRef.GetTable(Zemailrec);
        //----------------
        TempBlob.CreateOutStream(OutStr);

        //------
        TempBlob.CreateOutStream(OutStr);
        Message('Here in Code Unit');
        Report.SaveAs(ReportID, '', ReportFormat::Pdf, OutStr, RecRef);
        TempBlob.CreateInStream(InStrm);
        //---
        TempBlob.CREATEINSTREAM(Instr2_Chk);
        exit(FilePath);
    end;

    local procedure GetReportIDandLayoutCode(var ReportID: Integer; var LayoutCode: Code[20]; bulkMMBS: Record "BGS_Email Notices")
    var
        ReportSelections: Record "Report Selections";
    begin
        ReportSelections.SetRange(Usage, ReportSelections.Usage::"C.Statement");
        if ReportSelections.FindFirst then
            if bulkMMBS.Segment = 'BULK' then begin
                ReportID := 50101;
                LayoutCode := '50000-000001';
            end else begin
                ReportID := 50100;
                LayoutCode := '50000-000003';
            end;
        // ReportSelections.SETRANGE("Use for Email Body",TRUE);
        // IF ReportSelections.FINDFIRST THEN
        //  LayoutCode := ReportSelections."Email Body Layout Code";
    end;
}

-----
Please suggest mistakes..
  • Verified answer
    Govinda Kumar Profile Picture
    2,211 Moderator on at
    RE: Error while sending email with attachment on custom page

    you might want to use this code

        procedure SendEmailWithAttachments()
        var
            ReportParameters: Text;
            AttachmentTempBlob: Codeunit "Temp Blob";
            Rep50100: Report "Standard Sales - Invoice";
            AttachmentInStream: InStream;
            OutStr: OutStream;
            Subject: Text;
            "Send to": Text;
            FileName: Text;
            EmailMessage: Codeunit "Email Message";
            Email: Codeunit Email;
    
        begin
            "Send to" := 'abc181@outlook.com';
            Subject := 'XYZ';
            ReportParameters := Rep50100.RunRequestPage();
            AttachmentTempBlob.CreateOutStream(OutStr);
            // Rep50100.GetArgs(mailRec."Customer No", mailRec."Order No", mailRec."Price Date", WorkDate(), '');
    
            REPORT.SAVEAS(Report::"Standard Sales - Invoice", ReportParameters, REPORTFORMAT::Pdf, OutStr);
            AttachmentTempBlob.CreateInStream(AttachmentInStream);
            EmailMessage.Create("Send to", Subject, 'Price Notification');
            EmailMessage.AddAttachment('FilenameXYZ.pdf', 'PDF', AttachmentInStream);
            Email.Send(EmailMessage, Enum::"Email Scenario"::Default);
        end;
    

    Select your report instead of "Standard Sales - Invoice" in the code...

    Hopefully, it will help you.

  • Hafiz@d365 Profile Picture
    13 on at
    RE: Error while sending email with attachment on custom page

    Now the email is working and able to send but unable to add attachments.

    ------------------------------

           AttachmentTempBlob.CreateOutStream(OutStr);

               Rep50100.GetArgs(mailRec."Customer No", mailRec."Order No", mailRec."Price Date", WorkDate(), '');

               REPORT.SAVEAS(50100, '', REPORTFORMAT::Pdf, OutStr, RecRef);

               AttachmentTempBlob.CreateInStream(AttachmentInStream);

               EmailMessage.AddAttachment(Filename, 'PDF', AttachmentInStream);

               EmailMessage.Create("Send to", Subject, 'Price Notification');

               Email.Send(EmailMessage, Enum::"Email Scenario"::"Gas Price Email");

    ----------------------------------------

  • Suggested answer
    Govinda Kumar Profile Picture
    2,211 Moderator on at
    RE: Error while sending email with attachment on custom page

    Try running it with a debugger and see where it is breaking.. also it would be helpful if you share the code or screenshot of your error

    Regards

  • Hafiz@d365 Profile Picture
    13 on at
    RE: Error while sending email with attachment on custom page

    It was nice, thank you

    still, I have a problem with the following message. Please suggest

    -----

    The Tenant Media does not exist. Identification fields and values: ID='{00000000-0000-0000-0000-000000000000}'

    Internal session ID:

    4b0b566b-dba1-416a-b721-a173203f39b5

    Application Insights session ID:

    9661e097-55ec-4371-8f5f-3e9de7186fff

    Client activity id:

    fa72347a-87b9-4cc1-a1b5-c36d173018a0

    Time stamp on error:

    2023-04-15T15:45:11.9224684Z

    AL call stack:

    "Email Message Impl."(CodeUnit 8905).InsertAttachment line 5 - System Application by Microsoft

    "Email Message Impl."(CodeUnit 8905).AddAttachmentInternal line 5 - System Application by Microsoft

    "Email Message Impl."(CodeUnit 8905).AddAttachmentInternal line 4 - System Application by Microsoft

    "Email Message Impl."(CodeUnit 8905).AddAttachment line 2 - System Application by Microsoft

    "Email Message"(CodeUnit 8904).AddAttachment line 2 - System Application by Microsoft

    "BGS_Follow Email pattern"(CodeUnit 50100).SendSalesShipment line 60 - BGS-Cloud Project by Exceed - Bright Gas

    "BGS_Gas Price List"(Page 50169)."Send Email - OnAction"(Trigger) line 17 - BGS-Cloud Project by Exceed - Bright Gas

    --------

  • Suggested answer
    Govinda Kumar Profile Picture
    2,211 Moderator on at
    RE: Error while sending email with attachment on custom page

    Hi Hafiz,

    I had a similar requirement before, and I found a helpful blog post that might be useful for you as well businesscentralgeek.com/5-ways-to-send-an-email-in-business-central

    hope it helps

    Regards

  • Hafiz@d365 Profile Picture
    13 on at
    RE: Error while sending email with attachment on custom page

    Thank you for the information.

    Now the subject is going somewhere else indefinitely.

    I  have BC  online tenant where I have created file with PDF. I want to send it to the customer. I used code unit development. it is converted from on=prem to online. Here online, the 'file management' code unit  does not work

    I am not 100% technical. Just learned and began.  attached is the code also.

    suggest code correction, please..

    warm regards

    Hafiz

  • Suggested answer
    Govinda Kumar Profile Picture
    2,211 Moderator on at
    RE: Error while sending email with attachment on custom page

    Hi Hafiz@d365,

    As Mr Daniele Incalza said, it seems to be a problem related to media file that you are trying to attach, this blog post may help you simplanova.com/.../

  • Hafiz@d365 Profile Picture
    13 on at
    RE: Error while sending email with attachment on custom page

    I could not get

  • Suggested answer
    DAnny3211 Profile Picture
    9,274 Moderator on at
    RE: Error while sending email with attachment on custom page

    hi

    this error message indicates that the system is unable to locate the media file that you are trying to attach to your bulk email. The media file may have been deleted or its location may have changed, resulting in the system being unable to locate it.

    To resolve this issue, you can try the following steps:

    Check if the media file that you are trying to attach is still available in the location where it was stored before. If it has been deleted or moved, you may need to restore it or move it back to its original location.

    If the media file is still available, try uploading it again to the system and check if it is being recognized.

    If the above steps don't work, you can try to recreate the email and attach the file again. This may help to refresh the system and resolve any issues that might be preventing the media file from being recognized.

    Additionally, you can contact the technical support team of the application or system that you are using to send the bulk email with attachment

    DAniele

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

Daivat Vartak – Community Spotlight

We are honored to recognize Daivat Vartak as our March 2025 Community…

Announcing Our 2025 Season 1 Super Users!

A new season of Super Users has arrived, and we are so grateful for the daily…

Kudos to the February Top 10 Community Stars!

Thanks for all your good work in the Community!

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 292,886 Super User 2025 Season 1

#2
Martin Dráb Profile Picture

Martin Dráb 231,768 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156 Moderator

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans