Loading...

D365 FO Sending Email with SSRS reports as attachment using X++

D365 FO Sending Email with SSRS reports as attachment using X++

 Public class EmailCustAccountStmnt

{

public void run(CustTable _custTable)

{

SysOperationQueryDataContractInfo sysOperationQueryDataContractInfo;

SrsReportRunController reportRunController;

CustTransListContract custTransListContract;

SRSReportExecutionInfo reportExecutionInfo;

SRSPrintDestinationSettings printDestinationSettings;

SRSReportRunService srsReportRunService;

SRSProxy srsProxy;

QueryBuildRange qbrCustAccount;

QueryBuildDataSource queryBuildDataSource;

Object dataContractInfoObject;

Map reportParametersMap;

Map mapCustAccount;

MapEnumerator mapEnumerator;

Array arrayFiles;

System.Byte[] reportBytes;

Filename fileName;

Args args;

System.IO.MemoryStream memoryStream;

System.IO.MemoryStream fileStream;

CustParameters custParameters;

Email toEmail;

 

    Map                                 templateTokens;

    str                                 emailSenderName;

    str                                 emailSenderAddr;

    str                                 emailSubject;

    str                                 emailBody;

 

    Microsoft.Dynamics.AX.Framework.Reporting.Shared.ReportingService.ParameterValue[]  parameterValueArray;

 

    #define.Subject("Subject")

    #define.CustAccount("CustAccount")

    #define.EmailDate("Date");

 

    custParameters          = CustParameters::find();

 

    reportRunController     = new SrsReportRunController();

    custTransListContract   = new CustTransListContract();

    reportExecutionInfo     = new SRSReportExecutionInfo();

    srsReportRunService     = new SrsReportRunService();

    reportBytes             = new System.Byte[0]();

    args                    = new Args();

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

    var messageBuilder      = new SysMailerMessageBuilder();

 

    custTransListContract.parmNewPage(NoYes::Yes);

 

    fileName    = strFmt("CustomerAccountStatement_%1.pdf", _custTable.AccountNum);

 

    reportRunController.parmArgs(args);

    reportRunController.parmReportName(ssrsReportStr(CustTransList, Report));

    reportRunController.parmShowDialog(false);

    reportRunController.parmLoadFromSysLastValue(false);

    reportRunController.parmReportContract().parmRdpContract(custTransListContract);

 

    // Modify query

    mapCustAccount = reportRunController.getDataContractInfoObjects();

    mapEnumerator = mapCustAccount.getEnumerator();

 

    while (mapEnumerator.moveNext())

    {

        dataContractInfoObject = mapEnumerator.currentValue();

 

        if (dataContractInfoObject is SysOperationQueryDataContractInfo)

        {

            sysOperationQueryDataContractInfo = dataContractInfoObject;

 

            queryBuildDataSource    = SysQuery::findOrCreateDataSource(sysOperationQueryDataContractInfo.parmQuery()

                                                                    , tableNum(CustTable));

            qbrCustAccount          = SysQuery::findOrCreateRange(queryBuildDataSource, fieldNum(CustTable, AccountNum));

            qbrCustAccount.value(_custTable.AccountNum);

        }

    }

 

    printDestinationSettings = reportRunController.parmReportContract().parmPrintSettings();

    printDestinationSettings.printMediumType(SRSPrintMediumType::File);

    printDestinationSettings.fileName(fileName);

    printDestinationSettings.fileFormat(SRSReportFileFormat::PDF);

 

    reportRunController.parmReportContract().parmReportServerConfig(SRSConfiguration::getDefaultServerConfiguration());

    reportRunController.parmReportContract().parmReportExecutionInfo(reportExecutionInfo);

 

    srsReportRunService.getReportDataContract(reportRunController.parmreportcontract().parmReportName());

    srsReportRunService.preRunReport(reportRunController.parmreportcontract());

 

    reportParametersMap = srsReportRunService.createParamMapFromContract(reportRunController.parmReportContract());

    parameterValueArray = SrsReportRunUtil::getParameterValueArray(reportParametersMap);

 

    srsProxy        = SRSProxy::constructWithConfiguration(reportRunController.parmReportContract().parmReportServerConfig());

    reportBytes     = srsproxy.renderReportToByteArray(reportRunController.parmreportcontract().parmreportpath()

                                                    , parameterValueArray

                                                    , printDestinationSettings.fileFormat()

                                                    , printDestinationSettings.deviceinfo());

 

    memoryStream    = new System.IO.MemoryStream(reportBytes);

    memoryStream.Position = 0;

 

    fileStream      = memoryStream;

    toEmail         = this.getCustEmail(_custTable.AccountNum);

 

    if (custParameters.EmailId && toEmail)

    {

 

        templateTokens.insert(#CustAccount, _custTable.name());

        templateTokens.insert(#EmailDate, date2StrXpp(systemDateGet()));

 

        [emailSubject, emailBody, emailSenderAddr, emailSenderName] =

            EmailCustAccountStmnt::getEmailTemplate(custParameters.EmailId, _custTable.languageId());

 

 

        messageBuilder.addTo(this.getCustEmail(_custTable.AccountNum))

                        .setSubject(strFmt("Customer account statement for %1", _custTable.AccountNum))

                        .setBody(SysEmailMessage::stringExpand(emailBody, SysEmailTable::htmlEncodeParameters(templateTokens)))

                        .addCC("");

 

        messageBuilder.setFrom(emailSenderAddr, emailSenderName);

        messageBuilder.addAttachment(fileStream, fileName);

 

        SysMailerFactory::sendNonInteractive(messageBuilder.getMessage());

 

        info(strFmt("Email sent successfully to the customer account %1", _custTable.AccountNum));

    }

    else

    {

        info(strFmt("There is no email id mappiing for this customer %1 or check the Email template setup.", _custTable.AccountNum));

    }

}

 

protected static container getEmailTemplate(SysEmailId _emailId, LanguageId _languageId)

{

    var messageTable = SysEmailMessageTable::find(_emailId, _languageId);

    var emailTable = SysEmailTable::find(_emailId);

 

    if (!messageTable && emailTable)

    {

        // Try to find the email message using the default language from the email parameters

        messageTable = SysEmailMessageTable::find(_emailId, emailTable.DefaultLanguage);

    }

 

    if (messageTable)

    {

        return [messageTable.Subject, messageTable.Mail, emailTable.SenderAddr, emailTable.SenderName];

    }

    else

    {

        warning("@SYS135886"); // Let the user know we didn't find a template

        return ['', '', emailTable.SenderAddr, emailTable.SenderName];

    }

}

 

public Email getCustEmail(CustAccount _custAccount)

{

    CustTable                   custTable;

    DirPartyLocation            dirPartyLocation;

    LogisticsLocation           logisticsLocation;

    LogisticsElectronicAddress  logisticsElectronicAddress;

 

    custTable = CustTable::find(_custAccount);

 

    select firstonly Location, Party from dirPartyLocation

        where dirPartyLocation.Party                        == custTable.Party

            join RecId from logisticsLocation

                where logisticsLocation.RecId               == dirPartyLocation.Location

            join Locator from logisticsElectronicAddress

                where logisticsElectronicAddress.Location   == logisticsLocation.RecId

                    && logisticsElectronicAddress.Type      == LogisticsElectronicAddressMethodType::Email

                    && logisticsElectronicAddress.IsPrimary == NoYes::Yes;

 

    return logisticsElectronicAddress.Locator;

}

Published on:

Learn more
Need help with this product?

We can help you with D365 FO Sending Email with SSRS reports as attachment using X++

If you want help implementing, troubleshooting, or improving this product, contact us and we’ll point you in the right direction.

Sherif Fayed
Sherif Fayed

Share post:

Related posts

D365 Sending Email with Customer Account Statement SSRS report as attachment using X++

D365 Sending Email with Customer Account Statement SSRS report as attachment using X++ custTable _custTable;        &...

2 years ago

clicking link on info message X++ to Open form

 Message::AddAction() method can be used to embed an action within a message sent to the message bar. This method supports adding a singl...

2 years ago

D365 FO - Send Email with attachments by X++

 Go to System administration >> Setup >> Email >> System email templatesCreate New template [ExtensionOf(clas...

2 years ago

D365 FO Data entity Export using X++

This post provides information on exporting data entity through X++ in D365 FO. The post includes a code snippet written in X++ that can be us...

2 years ago

D365 FO Encryption And Decryption Using A Symmetric Key(AES) using X++

If you're looking to encrypt and decrypt data using a symmetric key in D365 FO, this tutorial is the right place to be. The post details the s...

2 years ago

Get multiple selected rows using D365 X++

This blog post offers a valuable insight into D365 X++, offering a detailed guide on how to get multiple selected rows. Multi-select for Butto...

2 years ago

D365 Solution for Cloud Dev machine show error ' The remote certificate is invalid according to the validation procedure. '

 You are getting 'The remote certificate is invalid according to the validation procedure.'Error show with all reports and  tired Ro...

2 years ago

Newsletter

Get the latest Dynamics 365 and Power Platform content in your inbox

A curated digest of community blogs, product news, videos, and podcasts — delivered without the noise.

Weekly updates Unsubscribe anytime Fresh community picks
We use your email only for the newsletter and you can unsubscribe at any time.
By subscribing, you agree to the privacy policy.