InstantiateTemplateResponse message in Dynamics CRM 2016
I had a heck of a time with the Microsoft documentation on this issue, so thought I would throw up a quick blog post to help anyone else with this task.
My work requirement:
Generate an email for all Active Organizations in Draft status. The email must have Excel files from Notes attached and use an existing Email Template.
There were many components to this problem that required a custom workflow rather than OOB functionality. For example: there will be more than 5000 Organizations queried, which meant needing a Paging Cookie as the data set was very large. I was also running another custom assembly that generated the Excel files for each Org and attached them to the Notes section. MS CRM OOB (Out of the box) provides no way to dynamically attach Note attachments to an email, so I would need to create the email programmatically and dynamically attach the documents.
My requirement was to generate the email in Draft status, preventing it from sending immediately, so I could not use the SendEmailFromTemplateRequest message which creates an email from a template and sends all in one step. Instead, I would need to use the InstantiateTemplateRequest message . The official documentation does not provide the hint that the email is not created, in fact it is only the email “message” which you’ll need to parse out of the Email Entity created, add to your Email and Create() with a CRM service call.
The InstantiateTemplateResponse class holds an EntityCollection (Email) with the Attributes of “subject” and “document” retrieved from the Email Template. In my code below, I assign these attributes to the Email’s Subject and Description, using a mix of Late and Early Bound entities.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
/** * Instantiates the email template and creates a new Email record * Returns the Guid of the new Email * */ private Guid createEmailWithTemplate(Entity emailTemplate) { InstantiateTemplateRequest instTemplateReq = new InstantiateTemplateRequest { TemplateId = emailTemplate.Id, ObjectId = _accountID, ObjectType = Account.EntityLogicalName }; InstantiateTemplateResponse instTemplateResp = (InstantiateTemplateResponse)service.Execute(instTemplateReq); Email instTemplate = (Email)instTemplateResp.EntityCollection.Entities[0]; //creates an Email with the template (empty TO/FROM fields) Email email = new Email { Subject = instTemplate.Attributes.Contains("subject") ? (String)instTemplate.Attributes["subject"] : "", Description = instTemplate.Attributes.Contains("description") ? (String)instTemplate.Attributes["description"] : "", DirectionCode = true }; Guid emailGuid = service.Create(email); return emailGuid; } |
I couldn’t find any code examples of this online, so hope it helps someone!