Thursday, August 15, 2019

How to change the email template content dynamically in Dynamic CRM


Here is an extracted code from a custom workflow where I am trying to send an email using Dynamic CRM SDK and C#.


// Creating a Template Request to get Template content
InstantiateTemplateRequest TemplateRequest = new InstantiateTemplateRequest();
TemplateRequest.TemplateId = this.Template.Get((ActivityContext)activityContext).Id;    // Template ID
TemplateRequest.ObjectId = this.Invoice.Get((ActivityContext)activityContext).Id;       // Entity ID (Invoice Id)
TemplateRequest.ObjectType =  "invoice";    // Entity

// Getting the template Object
Entity entity_EmailTemplate = ((InstantiateTemplateResponse)organizationService.Execute(TemplateRequest)).EntityCollection.Entities.FirstOrDefault();

// Populating Template Object with Email mandatory fields.
entity_EmailTemplate["from"] = new Entity[1]{entity_From};
entity_EmailTemplate["to"] = new Entity[1]{entity_To};
entity_EmailTemplate["subject"] =  this.Subject.Get((ActivityContext)activityContext);
entity_EmailTemplate["regardingobjectid"] = new EntityReference("invoice", this.Invoice.Get((ActivityContext)activityContext).Id);

// Email Body is already in template object
string str = entity_EmailTemplate["description"].ToString();

// Changing the email template content
entity_EmailTemplate["description"] = str.Replace("{!CustomerFirstName},", this.GetContactFirstName(organizationService, this.To.Get((ActivityContext)activityContext).Id) + ",");

// Creating Email Activity
Guid guid = organizationService.Create(entity_EmailTemplate);

// Sending an Email.
SendEmailRequest sendEmailRequest = new SendEmailRequest();
sendEmailRequest.EmailId = guid;                                  
sendEmailRequest.TrackingToken = "";    // Cleaning the Tracking Token
sendEmailRequest.IssueSend = true;
SendEmailResponse sendEmailResponse = (SendEmailResponse)organizationService.Execute((OrganizationRequest)sendEmailRequest);



Regards,
Vipin Jaiswal
vipinjaiswal12@gmail.com

1 comment:

Unknown said...

Nice article