Send Email Asynchronously in JavaScript from Windows Store Apps - HTML5 - UWP

In previous section, I introduced how to use event handler to monitor the progress. In this section, I will introduce how to send email asynchronously in JavaScript.

Introduction

In Windows Store App, all File or .NET IO operations are based on asynchronouse mode. You should use await keyword to wait the operation is finished. With asynchronouse mode, you can do other things in your codes while the email is sending. Please have a look at the following example codes:

Note

Remarks: All of samples in this section are based on first section: Send email in A simple JavaScript HTML5 Windows Store App project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference of EASendMail to your project.

[JavaScript - Send email in asynchronous mode]

The following example codes demonstrate how to use EASendMail SMTP component to send email in asynchronous mode.

Note

To get the full sample projects, please refer to Samples section.

(function () {
    "use strict";
    var appViewState = Windows.UI.ViewManagement.ApplicationViewState;
    var ui = WinJS.UI;
    var htmlinited = false;
    var editor;
    var asynCancel = null;
    var m_atts = new Array();
    ui.Pages.define("/default.html", {
        // This function is called whenever a user navigates to this page. It
        // populates the page elements with the app's data.
        ready: function (element, options) {
            init_gui();
        },

        unload: function () {

        }

    });

    function init_gui() {

        // add OnClick event handler
        var btn = document.getElementById("btnSend");
        btn.addEventListener("click", send_email, false);
    }

    function send_email() {
        var result = "";

        var oMail = new EASendMail.SmtpMail("TryIt");

        // Set sender email address, please change it to yours
        oMail.from = new EASendMail.MailAddress("test@emailarchitect.net");

        // Add recipient email address, please change it to yours
        oMail.to.add(new EASendMail.MailAddress("support@emailarchitect.net"));

        // Set email subject
        oMail.subject = "test email from JavaScript HTML5 project";

        // Set email body
        oMail.textBody = "this is a test email sent from Windows Store App, do not reply";

        // Your SMTP server address
        var oServer = new EASendMail.SmtpServer("smtp.emailarchitect.net");

        // User and password for ESMTP authentication
        oServer.user = "test@emailarchitect.net";
        oServer.password = "testpassword";

        // If your SMTP server requires TLS connection on 25 port, please add this line
        // oServer.connectType = EASendMail.SmtpConnectType.connectSSLAuto;

        // If your SMTP server requires SSL connection on 465 port, please add this line
        // oServer.port = 465;
        // oServer.connectType = EASendMail.SmtpConnectType.connectSSLAuto;

        var oSmtp = new EASendMail.SmtpClient();

        // EASendMail Events Handlers
        oSmtp.addEventListener("connected",
            (function (e) {
                var status = e.status;
                // status = "Connected";

                var textStatus = document.getElementById("textStatus");
                textStatus.innerText = status;
            }));

        oSmtp.addEventListener("authorized",
            (function (e) {
                var status = e.status;
                // status = "Authorized";

                var textStatus = document.getElementById("textStatus");
                textStatus.innerText = status;
            }));

        oSmtp.addEventListener("securing",
            (function (e) {
                var status = e.status;
                // status = "Securing ...";

                var textStatus = document.getElementById("textStatus");
                textStatus.innerText = status;
            }));

        oSmtp.addEventListener("sendingdatastream",
            (function (e) {
                var status = "Data " + e.sent + "/" + e.total + " sent";

                var textStatus = document.getElementById("textStatus");
                textStatus.innerText = status;

            }));

        var btn = document.getElementById("btnSend");
        btn.disabled = true;

        // get a asynchronous promise object
        var promise = oSmtp.sendMailAsync(oServer, oMail);

        // do some thing

        promise.done(function (e) {
            result = "Email was sent successfully!";

            //// Display Result by Diaglog box
            (new Windows.UI.Popups.MessageDialog(result, "Success")).showAsync();
            btn.disabled = false;
        },

        function (e) {
            //// because javascript exception only gives the stack trace messages, but it is not
            // real description of exception, so we give a property lastErrorMessage for javascript.
            if (oSmtp.lastErrorMessage != "") {
                result = oSmtp.lastErrorMessage;
            }
            else {
                result = e.message;
            }
            oSmtp.close();

            // Display Result by Diaglog box
            (new Windows.UI.Popups.MessageDialog(result, "Error Information")).showAsync();
            btn.disabled = false;
        });
    }
})();

Cancel Asynchronous Operation

In above codes, SendMailAsync method returns a IAsyncAction object, we can also use this object to cancel current email sending. Please have a look at the following codes:

(function () {
    "use strict";
    var appViewState = Windows.UI.ViewManagement.ApplicationViewState;
    var ui = WinJS.UI;
    var htmlinited = false;
    var editor;
    var asynCancel = null;
    var m_atts = new Array();
    ui.Pages.define("/default.html", {
        // This function is called whenever a user navigates to this page. It
        // populates the page elements with the app's data.
        ready: function (element, options) {
            init_gui();
        },

        unload: function () {

        }

    });

    function init_gui() {

        // add OnClick event handler
        var btn = document.getElementById("btnSend");
        btn.addEventListener("click", send_email, false);

        // add Cancel event handler
        btn = document.getElementById("btnCancel");
        btn.addEventListener("click", (function (e) {
            this.disabled = true;
            if (asynCancel != null) {// cancel operation
                asynCancel.cancel();
            }
        }), false);
    }

    function send_email() {
        var result = "";

        var oMail = new EASendMail.SmtpMail("TryIt");

        // Set sender email address, please change it to yours
        oMail.from = new EASendMail.MailAddress("test@emailarchitect.net");

        // Add recipient email address, please change it to yours
        oMail.to.add(new EASendMail.MailAddress("support@emailarchitect.net"));

        // Set email subject
        oMail.subject = "test email from JavaScript HTML5 project";

        // Set email body
        oMail.textBody = "this is a test email sent from Windows Store App, do not reply";

        // Your SMTP server address
        var oServer = new EASendMail.SmtpServer("smtp.emailarchitect.net");

        // User and password for ESMTP authentication
        oServer.user = "test@emailarchitect.net";
        oServer.password = "testpassword";

        // If your SMTP server requires TLS connection on 25 port, please add this line
        // oServer.connectType = EASendMail.SmtpConnectType.connectSSLAuto;

        // If your SMTP server requires SSL connection on 465 port, please add this line
        // oServer.port = 465;
        // oServer.connectType = EASendMail.SmtpConnectType.connectSSLAuto;

        var oSmtp = new EASendMail.SmtpClient();

        // EASendMail Events Handlers
        oSmtp.addEventListener("connected",
            (function (e) {
                var status = e.status;
                // status = "Connected";

                var textStatus = document.getElementById("textStatus");
                textStatus.innerText = status;
            }));

        oSmtp.addEventListener("authorized",
            (function (e) {
                var status = e.status;
                // status = "Authorized";

                var textStatus = document.getElementById("textStatus");
                textStatus.innerText = status;
            }));

        oSmtp.addEventListener("securing",
            (function (e) {
                var status = e.status;
                // status = "Securing ...";

                var textStatus = document.getElementById("textStatus");
                textStatus.innerText = status;
            }));

        oSmtp.addEventListener("sendingdatastream",
            (function (e) {
                var status = "Data " + e.sent + "/" + e.total + " sent";

                var textStatus = document.getElementById("textStatus");
                textStatus.innerText = status;

            }));

        asynCancel = null;
        document.getElementById("btnSend").disabled = true;
        document.getElementById("btnCancel").disabled = false;

        // get asynchronous cancellation object
        asynCancel =  oSmtp.sendMailAsync(oServer, oMail).then(function (e) {
            result = "Email was sent successfully!";

            // Display Result by Diaglog box
            (new Windows.UI.Popups.MessageDialog(result, "Success")).showAsync();

            document.getElementById("btnSend").disabled = false;
            document.getElementById("btnCancel").disabled = true;
        },

        function (e) {
            // because javascript exception only gives the stack trace messages, but it is not
            // real description of exception, so we give a property lastErrorMessage for javascript.
            if (oSmtp.lastErrorMessage != "") {
                result = oSmtp.lastErrorMessage;
            }
            else {
                result = e.message;
            }
            oSmtp.close();

            // Display Result by Diaglog box
            (new Windows.UI.Popups.MessageDialog(result, "Error Information")).showAsync();

            document.getElementById("btnSend").disabled = false;
            document.getElementById("btnCancel").disabled = true;
        });
    }
})();

Next Section

At next section I will introduce how to send email using Exchange Web Service - EWS.

Appendix

Comments

If you have any comments or questions about above example codes, please click here to add your comments.