Instantiating an email template with Web API

By | April 4, 2019

There is email template functionality in Dynamics/model-driven applications – if you are not familiar with it, have a look at the documentation first:

However, what if, for whatever reason, you wanted to automatically instantiate an email template instead of having to use “insert template button” on the email screen?

For example, maybe there are a few frequently used templates, so you might want to add a flyout button to the command bar as a shortcut for those templates.

This is what you can use InsantiateTemplate action for:

And below is a javascript code sample which will do just that, just make sure to

  • Replace those parameters with the propert templateid, objecttype, and object id
  • Instead of displaying the alerts, do something with the subject and description you will get back from the action call
function InstantiateEmailTemplate()
    var parameters = {
        "TemplateId": "00000000-0000-0000-0000-000000000000",//GUID
        "ObjectType": "logicalname",//Entity logical name, lowercase
        "ObjectId": "00000000-0000-0000-0000-000000000000"//record id for the entity above

    var requestUrl = "/api/data/v9.1/InstantiateTemplate";
    var context;
    if (typeof GetGlobalContext === "function") {
        context = GetGlobalContext();
    } else {
        context = Xrm.Page.context;

    var req = new XMLHttpRequest();"POST", context.getClientUrl() + requestUrl, true);
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.onreadystatechange = function () {
        if (this.readyState === 4) {
            req.onreadystatechange = null;
            if (this.status === 200) {
                var result = JSON.parse(this.response);
            } else {
                var errorText = this.responseText;

PS. Here is the terrible part.. I’ve written the post above, and, then, a colleague of mine came up and said “Hey, I found this other post:  ”

Of course, those Inogic folks.. they even have the same blog theme! Well, maybe I have the same.. Anyway, I figured I’d count the number of lines in each version and you know what? If you remove empty lines and alerts in my version, it turns out to be a shorter one! Well, the old ways are not, always, worse, but they are still old 🙂 So, make sure to read that post by Inogic.

Leave a Reply

Your email address will not be published. Required fields are marked *