Create Email Activity from Template using Javascript

Here is a nice piece of code to create an email from a specified email template using Javascript and also set the Email to field. Its slightly unrefined but good to go and a great starting point. It is great functionality if you choose to add a menu button to an entity in the ISV.config or similar and loads almost instantly.


//
// Create Email From template with the specified customer and regarding entity
//
CreateEmailFromTemplate = function(Customer, TemplateId, EntityId, EntityTypeName) {
// Generate an email activity from the specified template
//
var xml = "" +
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"&lt;soap:Envelope xmlns:soap=\"<a href="//schemas.xmlsoap.org/soap/envelope/\&quot;">http://schemas.xmlsoap.org/soap/envelope/\</a>" xmlns:xsi=\"<a href="//www.w3.org/2001/XMLSchema-instance\&quot;">http://www.w3.org/2001/XMLSchema-instance\</a>" xmlns:xsd=\"<a href="//www.w3.org/2001/XMLSchema\&quot;">http://www.w3.org/2001/XMLSchema\</a>"&gt;" +
GenerateAuthenticationHeader() +
" &lt;soap:Body&gt;" +
" &lt;Execute xmlns=\"<a href="//schemas.microsoft.com/crm/2007/WebServices\&quot;">http://schemas.microsoft.com/crm/2007/WebServices\</a>"&gt;" +
" &lt;Request xsi:type='InstantiateTemplateRequest' ReturnDynamicEntities='false' &gt;"+
" &lt;TemplateId&gt;" + TemplateId + "&lt;/TemplateId&gt;"+
" &lt;ObjectType&gt;" + EntityTypeName + "&lt;/ObjectType&gt;"+
" &lt;ObjectId&gt;" + EntityId + "&lt;/ObjectId&gt;"+
" &lt;/Request&gt;"+
" &lt;/Execute&gt;" +
" &lt;/soap:Body&gt;" +
"&lt;/soap:Envelope&gt;";
var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xmlHttpRequest.setRequestHeader("SOAPAction", "<a href="//schemas.microsoft.com/crm/2007/WebServices/Execute&quot;">http://schemas.microsoft.com/crm/2007/WebServices/Execute</a>");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest.send(xml);
var resultXml = xmlHttpRequest.responseXML;
var entityNode = resultXml.selectSingleNode("//BusinessEntityCollection/BusinessEntities/BusinessEntity");
if(entityNode == null)
{
alert("Could not create email from template.");
return;
}
// Get the email details
var emailBody = entityNode.selectSingleNode("q1:description");
var subject = entityNode.selectSingleNode("q1:subject");
//
// Create email activity in CRM
//
var emailXml = "&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;" +
"&lt;soap:Envelope xmlns:soap=\"<a href="//schemas.xmlsoap.org/soap/envelope/\&quot;">http://schemas.xmlsoap.org/soap/envelope/\</a>" xmlns:xsi=\"<a href="//www.w3.org/2001/XMLSchema-instance\&quot;">http://www.w3.org/2001/XMLSchema-instance\</a>" xmlns:xsd=\"<a href="//www.w3.org/2001/XMLSchema\&quot;">http://www.w3.org/2001/XMLSchema\</a>"&gt;" +
GenerateAuthenticationHeader() +
"&lt;soap:Body&gt;" +
"&lt;Create xmlns='http://schemas.microsoft.com/crm/2007/WebServices'&gt;" +
"&lt;entity xsi:type='email'&gt;" +
"&lt;description&gt;" + emailBody.text + "&lt;/description&gt;" +
"&lt;subject&gt;" + subject.text + "&lt;/subject&gt;" +
"&lt;regardingobjectid type='" + EntityTypeName + "'&gt;" + EntityId + "&lt;/regardingobjectid&gt;";
if(Customer != null)
emailXml = emailXml + "&lt;to&gt;&lt;activityparty&gt;&lt;partyid type='" + Customer[0].typename + "'&gt;" + Customer[0].id + "&lt;/partyid&gt;&lt;/activityparty&gt;&lt;/to&gt;";
emailXml = emailXml + "&lt;/entity&gt;" +
"&lt;/Create&gt;" +
"&lt;/soap:Body&gt;" +
"&lt;/soap:Envelope&gt;";
xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xmlHttpRequest.setRequestHeader("SOAPAction", "<a href="//schemas.microsoft.com/crm/2007/WebServices/Create&quot;">http://schemas.microsoft.com/crm/2007/WebServices/Create</a>");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest.send(emailXml);
var resultEmailXml = xmlHttpRequest.responseXML;
// Check for errors.
var errorCount = resultEmailXml.selectNodes('//error').length;
if (errorCount &gt; 0)
{
alert("Could not create email due to error. ");
return;
}
var createNode = resultEmailXml.selectSingleNode("//CreateResult");
if(createNode == null)
{
alert("Could not create email.");
return;
}
// Display the email activity to the user.
var emailId = createNode.text;
window.open('/activities/email/edit.aspx?id={' + emailId + '}');
} // CreateEmailFromTemplate

You can use this function to retrieve a template id by specifying a template name/title.

//
// Retrieve the template's id value given the specified template name/title
//
GetTemplateIdByName = function(Name)
{
var id = null;
var xml = "" +
"&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;" +
"&lt;soap:Envelope xmlns:soap=\"<a href="//schemas.xmlsoap.org/soap/envelope/\&quot;">http://schemas.xmlsoap.org/soap/envelope/\</a>" xmlns:xsi=\"<a href="//www.w3.org/2001/XMLSchema-instance\&quot;">http://www.w3.org/2001/XMLSchema-instance\</a>" xmlns:xsd=\"<a href="//www.w3.org/2001/XMLSchema\&quot;">http://www.w3.org/2001/XMLSchema\</a>"&gt;" +
GenerateAuthenticationHeader() +
" &lt;soap:Body&gt;" +
" &lt;RetrieveMultiple xmlns=\"<a href="//schemas.microsoft.com/crm/2007/WebServices\&quot;">http://schemas.microsoft.com/crm/2007/WebServices\</a>"&gt;" +
" &lt;query xmlns:q1=\"<a href="//schemas.microsoft.com/crm/2006/Query\&quot;">http://schemas.microsoft.com/crm/2006/Query\</a>" xsi:type=\"q1:QueryExpression\"&gt;" +
" &lt;q1:EntityName&gt;template&lt;/q1:EntityName&gt;" +
" &lt;q1:ColumnSet xsi:type=\"q1:ColumnSet\"&gt;" +
" &lt;q1:Attributes&gt;" +
" &lt;q1:Attribute&gt;templateid&lt;/q1:Attribute&gt;" +
" &lt;/q1:Attributes&gt;" +
" &lt;/q1:ColumnSet&gt;" +
" &lt;q1:Criteria&gt;" +
" &lt;q1:FilterOperator&gt;And&lt;/q1:FilterOperator&gt;" +
" &lt;q1:Conditions&gt;" +
" &lt;q1:Condition&gt;" +
" &lt;q1:AttributeName&gt;title&lt;/q1:AttributeName&gt;" +
" &lt;q1:Operator&gt;Equal&lt;/q1:Operator&gt;" +
"&lt;q1:Values&gt;" +
"&lt;q1:Value xsi:type='xsd:string'&gt;" + Name + "&lt;/q1:Value&gt;" +
"&lt;/q1:Values&gt;" +
" &lt;/q1:Condition&gt;" +
" &lt;/q1:Conditions&gt;" +
" &lt;/q1:Criteria&gt;" +
" &lt;/query&gt;" +
" &lt;/RetrieveMultiple&gt;" +
" &lt;/soap:Body&gt;" +
"&lt;/soap:Envelope&gt;";
var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xmlHttpRequest.setRequestHeader("SOAPAction", "<a href="//schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple&quot;">http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple</a>");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest.send(xml);
var resultXml = xmlHttpRequest.responseXML;
var entityNode = resultXml.selectSingleNode("//RetrieveMultipleResult/BusinessEntities/BusinessEntity");
if(entityNode.selectSingleNode("q1:templateid") != null)
id = entityNode.selectSingleNode("q1:templateid").text;
return id;
} // GetTemplateIdByName

The following code provides an example of a function that can be called to execute the above functionality. The example assumes you have placed all of the code from this article in the Case's onload event. You can then call the ShowCaseEmailTemplate() function from an ISV.config button or wherever you choose to decide you need it.

//
// Creates and displays an email for a Case
//
ShowCaseEmailTemplate = function()
{
var templateId = GetTemplateIdByName("MyEmailTemplate");
if(templateId != null &amp;&amp; crmForm.ObjectId != null &amp;&amp; crmForm.all.customerid.DataValue != null)
CreateEmailFromTemplate(crmForm.all.customerid.DataValue, templateId, crmForm.ObjectId, "incident");
} // ShowCaseEmailTemplate

Advertisements

About Rhett Clinton MVP
Dynamics CRM MVP

8 Responses to Create Email Activity from Template using Javascript

  1. mardukes says:

    I tried this for a couple of days before finding your example. I could not get the InstantiateTemplateRequest to fire. I had apostrophes within all the substrings. Even your code wouldn’t work until I replaced ALL of them with quotation marks. Any idea why my was more finnicky than yours let alone finnicky at all?

    • Hi mardukes,

      I did find while trying to get this to work originally that the attributes TemplateId, ObjectType and ObjectId all had to be in this specific order.

      <Request xsi:type='InstantiateTemplateRequest' ReturnDynamicEntities='false' >"+
      " <TemplateId>" + TemplateId + "</TemplateId>"+
      " <ObjectType>" + EntityTypeName + "</ObjectType>"+
      " <ObjectId>" + EntityId + "</ObjectId>"+
      " </Request>"+

      With regards to the quote/apos issue I think my blog post may have converted them incorrectly automatically so I’ve updated it now to use the HTML character codes (Which now seem to show correctly) so you should be able to copy and paste without updating these characters.

      • mardukes says:

        I don’t think it was the order, though order did change the error message. But I wasn’t talking about the “smart” quotes in your article vs “raw” quotation marks. I’m talking about having to change type=’InstantiateTemplateRequest’ to type=\”Inst…st\”. This is doubly bizarre because it not only is stricter than xml standards but I started cutting and pasting the soap from the SDK where apostrophes are used.

  2. Faisal says:

    Hi Rhett,
    Thank you for posting such a useful article. I have been trying to create a email using the above code. It works fine when I don’t pass email body from the template. When I pass emailbody from the template I get error message. I have alerted the emailBody.text and it is showing in html format. If I use a function to strip HTML than the email is create fine however it trips all the formatting and I get a description in one paragraph. I am suspecting it might be at my end only. Can you please suggest anything?
    Regards
    Faisal Fiaz

  3. Faisal says:

    After doing some more dig up I found that I am able to create email using this replace command:-
    var result = emailBody.replace(//g, “”);
    But I lose formatting.

  4. Faisal says:

    var result = emailBody.replace(//g, “”);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: