The email templates in MS CRM can be leveraged as a powerful building block when generating emails programmatically.
- Generate your HTML in another editor and then paste it into the template editor to add data slugs.
- Associate your template with the entity that you want the most information from.
- Use Template Naming conventions that organize things and make programmatic template selection easier.
For an example lets say that we have product specific Quote Letters.
Using my helper method from a previous blog article, grab an email template matching a specific name based on the product.
Then create a new InstantiateTemplateRequest using the template id and point it at an entity with the information that you want merged in. This must be the same type that you associated your template with when you created it.
The result of the InstantiateTemplateResponse is an email entity collection. For this example we just have one email.
From here you can regard the email to a completely different entity if you want. It is only important that the ObjectId and ObjectType be set for the merge process. After that is complete this is just another email with a bunch of fields pre-filled. Now you can have your way with it like any other email that you created from scratch. This is critical to making the best use of email templates.
If you are calculating other numbers or pulling information from another data source outside of CRM, there is no reason to limit merging to what can be represented as data slugs.
In this example I am using putting additional information into the email body with a simple string replace using an agreed upon naming convention to represent additional merge fields.
From here you can add attachments as shown here.
Proofing before Email is Sent
Another useful thing to do if you are doing this in a web application or a client Winform application is save the email and then open it in a new window for final review before it is sent. To do that generate a URL like the following with your orgname and email id passed in. You can get the CRM server base URL from the registry as shown here which you need for your web service reference, and then use the following: CrmServerBaseUrl = CrmServiceUrl.Substring(0, CrmServiceUrl.ToLower().IndexOf("mscrmservices"));
From a WinForm application you can pop a CRM screen up like this.