Running a Content Creation Operation for Email By Data Record (Using JSON)

Problem

You want to run a content creation operation to create and potentially send email content using a template and an existing set of Data Records as inputs.

Solution

The solution is to make a series of requests using the following URIs and method types to submit, monitor progress and ultimately retrieve the result of the content creation operation. There is also the option of cancelling an operation during processing if required. These requests can be submitted via the Content Creation (Email) REST service:

Process Content Creation (By Data Record) (JSON) /rest/serverengine/workflow/contentcreation/email/{templateId} POST
Get Progress of Operation /rest/serverengine/workflow/contentcreation/email/getProgress/{operationId} GET
Get Result of Operation /rest/serverengine/workflow/contentcreation/email/getResult/{operationId} POST
Cancel an Operation /rest/serverengine/workflow/contentcreation/email/cancel/{operationId} POST

Example

HTML5

cce-process-by-dre-json.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Process Content Creation (By Data Record) (JSON) Example</title>
        <script src="../../common/lib/js/jquery-3.4.1.min.js"></script>
        <script src="../../common/js/common.js"></script>
        <script src="js/cce-process-by-dre-json.js"></script>
        <link rel="stylesheet" href="../../common/css/styles.css">
    </head>
    <body>
        <h2>Content Creation (Email) Service - Process Content Creation (By Data Record) (JSON) Example</h2>
        <form>
            <fieldset>
                <legend>Inputs</legend>
                <div>
                    <label for="datarecords">Data Record ID(s):</label>
                    <input id="datarecords" type="text" placeholder="1234, 2345, 3456, ..." required>
                </div>
                <div>
                    <label for="template">Template ID/Name:</label>
                    <input id="template" type="text" placeholder="1234 or Filename" required>
                </div>
            </fieldset>
            <fieldset>
                <legend>Email Parameters</legend>
                <div>
                    <label for="section">Section:</label>
                    <input id="section" type="text" placeholder="Section Name">
                </div>
                <div>
                    <label for="sender">From:</label>
                    <input id="sender" type="text" placeholder="mailbox@domain.com" required>
                </div>
                <div>
                    <label for="sendername">From Name:</label>
                    <input id="sendername" type="text" placeholder="From Name">
                </div>
                <div>
                    <label for="host">Host:</label>
                    <input id="host" type="text" placeholder="mail.domain.com:port">
                </div>
                <div>
                    <label for="usesender">Use From as To Email Address:</label>
                    <input id="usesender" type="checkbox" checked>
                </div>
                <div>
                    <label for="attachpdf">Attach Print Context as PDF:</label>
                    <select id="attachpdf">
                        <option value="default">Default</option>
                        <option value="true">True</option>
                        <option value="false">False</option>
                    </select>
                </div>
                <div>
                    <label for="attachweb">Attach Web Context as HTML:</label>
                    <input id="attachweb" type="checkbox">
                </div>
                <div>
                    <label for="eml">Add EML of Email:</label>
                    <input id="eml" type="checkbox">
                </div>
            </fieldset>
            <fieldset>
                <legend>Email Security</legend>
                <div>
                    <label for="useauth">Use Authentication:</label>
                    <input id="useauth" type="checkbox" checked>
                </div>
                <div>
                    <label for="starttls">Start TLS:</label>
                    <input id="starttls" type="checkbox">
                </div>
                <div>
                    <label for="username">Username:</label>
                    <input id="username" type="text" placeholder="Username">
                </div>
                <div>
                    <label for="password">Password:</label>
                    <input id="password" type="password" placeholder="Password">
                </div>
            </fieldset>
            <fieldset>
                <legend>Progress &amp; Actions</legend>
                <div>
                    <progress value="0" max="100"></progress>
                </div>
                <div>
                    <input id="cancel" type="button" value="Cancel" disabled>
                    <input id="submit" type="submit" value="Submit">
                </div>
            </fieldset>
        </form>
    </body>
</html>

JavaScript/jQuery

cce-process-by-dre-json.js

/* Content Creation (Email) Service - Process Content Creation (By Data Record) (JSON) Example */
(function ($, c) {
    "use strict";
    $(function () {

        c.setupExample();

        var $sender = $("#sender"),
            $senderName = $("#sendername"),
            $useSender = $("#usesender"),
            $host = $("#host"),
            $eml = $("#eml"),
            $useAuth = $("#useauth"),
            $startTLS = $("#starttls"),
            $username = $("#username"),
            $password = $("#password"),
            $submitButton = $("#submit"),
            $cancelButton = $("#cancel"),
            $progressBar = $("progress"),
            operationId = null;

        $cancelButton.on("click", function () {
            if (operationId !== null) {

                /* Cancel an Operation */
                $.ajax({
                    type: "POST",
                    url:  "/rest/serverengine/workflow/contentcreation/email/cancel/" + operationId
                })
                    .done(function (response) {
                        c.displayInfo("Operation Cancelled!");
                        operationId = null;
                        setTimeout(function () {
                            $progressBar.attr("value", 0);
                            $submitButton.prop("disabled", false);
                            $cancelButton.prop("disabled", true);
                        }, 100);
                    })
                    .fail(c.displayDefaultFailure);
            }
        });

        $sender
            .on("change", function (event) {
                var sender = event.target.value.trim(),
                    disabled = $(event.target).prop("disabled");
                $senderName.prop("disabled", (disabled || !sender.length));
                $useSender.prop("disabled", (disabled || !sender.length));
            })
            .trigger("change");

        $host
            .on("change", function (event) {
                var host = event.target.value.trim();
                $useAuth
                    .prop("disabled", !host.length)
                    .trigger("change");
                $sender
                    .prop("disabled", !host.length)
                    .trigger("change");
                $eml
                    .prop("disabled", host.length)
                    .trigger("change");
            })
            .trigger("change");

        $eml
            .on("change", function (event) {
                if (!$host.val().trim().length)
                    $sender
                        .prop("disabled", !$(event.target).prop("checked"))
                        .trigger("change");
            })
            .trigger("change");

        $useAuth
            .on("change", function (event) {
                var checked = ($(event.target).prop("checked")),
                    disabled = ($(event.target).prop("disabled"));
                $.each([$startTLS, $username, $password], function (index, $element) {
                    $element.prop("disabled", (disabled || !checked));
                });
            })
            .trigger("change");

        $("form").on("submit", function (event) {

            event.preventDefault();
            if (!c.checkSessionValid()) return;

            var dataRecordIds = $("#datarecords").val(),
                templateId = $("#template").val(),
                section = $("#section").val().trim(),
                host = $host.val().trim();

            var getFinalResult = function () {

                /* Get Result of Operation */
                $.ajax({
                    type: "POST",
                    url:  "/rest/serverengine/workflow/contentcreation/email/getResult/" + operationId
                })
                    .done(function (response, status, request) {
                        c.displayHeading("Operation Result");
                        if (host.length)
                            c.displaySubResult("Email Report", response);
                        else
                            c.displaySubResult("JSON Email Output List",
                                c.jsonPrettyPrint(response));
                    })
                    .fail(c.displayDefaultFailure);
            };

            /* Construct JSON Identifier List (with Email Parameters) */
            var config = {
                    "identifiers": (c.plainIDListToJson(dataRecordIds)).identifiers
                },
                sender = $sender.val(),
                attachPdfPage = $("#attachpdf").val();

            if (!$sender.prop("disabled") && sender.length) {
                config.sender = sender;
                var senderName = $senderName.val().trim();
                if (senderName.length) config.senderName = senderName;
                if ($useSender.prop("checked")) config.useSender = true;
            }

            if (host.length) {
                config.host = host;
                if ($useAuth.prop("checked")) config.useAuth = true;
                if (config.useAuth) {
                    if ($startTLS.prop("checked")) config.useStartTLS = true;
                    config.user = $username.val();
                    config.password = $password.val();
                }
            } else {
                if ($eml.prop("checked")) config.eml = true;
            }

            if (attachPdfPage !== "default")
                config.attachPdfPage = (attachPdfPage === "true");
            if ($("#attachweb").prop("checked"))
                config.attachWebPage = true;

            /* Process Content Creation (By Data Record) (JSON) */
            var settings = {
                type:        "POST",
                url:         "/rest/serverengine/workflow/contentcreation/email/" + templateId,
                data:        JSON.stringify(config),
                contentType: "application/json"
            };
            if (section.length) settings.url += "?section=" + section;
            $.ajax(settings)
                .done(function (response, status, request) {

                    var progress = null;
                    operationId = request.getResponseHeader("operationId");

                    $submitButton.prop("disabled", true);
                    $cancelButton.prop("disabled", false);

                    c.displayStatus("Content Creation Operation Successfully Submitted");
                    c.displayResult("Operation ID", operationId);

                    var getProgress = function () {
                        if (operationId !== null) {

                            /* Get Progress of Operation */
                            $.ajax({
                                type:  "GET",
                                cache: false,
                                url:   "/rest/serverengine/workflow/contentcreation/email/getProgress/" + operationId
                            })
                                .done(function (response, status, request) {

                                    if (response !== "done") {
                                        if (response !== progress) {
                                            progress = response;
                                            $progressBar.attr("value", progress);
                                        }
                                        setTimeout(getProgress, 1000);
                                    } else {
                                        $progressBar.attr("value", (progress = 100));
                                        c.displayInfo("Operation Completed");
                                        getFinalResult();
                                        operationId = null;
                                        setTimeout(function () {
                                            $progressBar.attr("value", 0);
                                            $submitButton.prop("disabled", false);
                                            $cancelButton.prop("disabled", true);
                                        }, 100);
                                    }
                                })
                                .fail(c.displayDefaultFailure);
                        }
                    };
                    getProgress();
                })
                .fail(c.displayDefaultFailure);
        });
    });
}(jQuery, Common));

Screenshot & Output

Usage

To run the example you first need to enter a comma delimited list of your Data Record IDs and the Managed File ID or Name of your template (previously uploaded to the file store) into the appropriate text fields as your inputs.

The example can then be configured (via the specification of email parameters) to run in one of two ways:

  • Create email output to the Connect File Store.

  • Create email output directly to a SMTP mail server.

By default, the example will create email output to the file store, but by specifying the Host email parameter the example can be run to create email output directly to a SMTP mail server.

Creating Email Output to the Connect File Store

When creating email output to the file store, the following email parameters can be specified for use with the content creation operation:

  • Add EML of Email – Create an EML (E-Mail Message) file of the email for each record in the email output.

If the Add EML of Email field is checked, then the following email parameter must also be specified:

  • From – the email address to be shown as the sender in the email output

Creating Email Output Directly to a SMTP Mail Server

When creating email output directly to a SMTP mail server, the following email parameters must be specified for use with the content creation operation:

  • Host – the network address or name of your SMTP mail server through which the emails will be sent. If required, a server port value can also be specified.

  • From – the email address to be shown as the sender in the email output.

Common to both forms of email output, the following email parameters can be specified for use with the content creation operation:

  • Section – the section within the Email context of the template to use.

  • Attach Print Context as PDF – if a Print context exists in the template, create its output as a PDF file and attach it to the email output (Default value depends on Template).

  • Attach Web Context as HTML – if a Web context exists in the template, create output of its enabled sections (a single section by default) as HTML files and attach them to the email output.

Common to both forms of email output, if the From field is populated, then the following email parameters can also be specified:

  • From Name – the name to be shown as the sender in the email output.

  • Use From as To Email Address – use the sender address as the receiver address for all emails in the output.

Finally, if creating email output directly to a SMTP mail server, you need to specify how email security is to be used with the content creation operation:

  • Use Authentication – if authentication is to be used with the mail server.

  • Start TLS – if Transport Layer Security (TLS) is to be opportunistically used when sending emails.

  • Username – the username to authenticate/login with.

  • Password – the password to authenticate/login with.

Lastly, select the Submit button to start the content creation operation.

Once the operation has started processing, the Operation ID will be displayed in the Results area and the Cancel button will become enabled, giving you the option to cancel the running operation.

The progress of the operation will be displayed in the progress bar, and once the content creation operation has completed, an operation result will be returned and displayed to the Results area.

If creating email output to the file store, a report of the emails successfully created will be returned in JSON Email Output List format. Alternatively, creating email output directly to a SMTP mail server will return a simple report of the emails successfully created and sent.

Further Reading

See the Content Creation (Email) Service page of the REST API Reference section for further detail.