Sample code to use Template’s content while sending mail using SendEmailReuquest in CRM 2011

Hi,

At times we would like to send email using SendEmailRequest but still want to make use of template and replace the content in it.

For e.g. this is our sample template (Global template)

Here we would replace the [subject] and [url] placeholders.

Sample Code used


private void SendMail(object sender, EventArgs e)
 {
 IOrganizationService orgService = GetOrganizationService();
 Entity entity = GetGlobalTemplate("My Test Template", GetOrganizationService());
 Entity email = new Entity();
 email.LogicalName = "email";

// get the Subject content from template and replace it with "My New Subject"
 email.Attributes["subject"] = GetDataFromXml(entity.Attributes["subject"].ToString(), "match");
 email.Attributes["subject"] = email.Attributes["subject"].ToString().Replace("[subject]", "My New Subject");

// get the description from template and replace [url] placeholder with a bing's url
 email.Attributes["description"] = GetDataFromXml(entity.Attributes["body"].ToString(), "match");
 string urlToReplace = "<a href='http://www.bing.com'>Open Bing</a>";
 email.Attributes["description"] = email.Attributes["description"].ToString().Replace("[url]", urlToReplace);

List<Entity> fromtoEntities = new List<Entity>();
 Entity activityParty = new Entity();
 activityParty.LogicalName = "activityparty";
 activityParty.Attributes["partyid"] = new EntityReference("systemuser", new Guid("FC480E73-77A9-E111-B151-00155D882D40"));
 fromtoEntities.Add(activityParty);
 email.Attributes["from"] = fromtoEntities.ToArray();
 email.Attributes["to"] = fromtoEntities.ToArray();
 email.Attributes["regardingobjectid"] = new EntityReference("contact", new Guid("2CCB57AA-A9B3-E111-B151-00155D882D40"));

Guid emailCreated = orgService.Create(email);
 SendEmailRequest req = new SendEmailRequest();
 req.EmailId = emailCreated;
 req.TrackingToken = "";
 req.IssueSend = true;
 SendEmailResponse res = (SendEmailResponse)orgService.Execute(req);
 }

private static string GetDataFromXml(string value, string attributeName)
 {
 if (string.IsNullOrEmpty(value))
 {
 return string.Empty;
 }

XDocument document = XDocument.Parse(value);
 // get the Element with the attribute name specified
 XElement element = document.Descendants().Where(ele => ele.Attributes().Any(attr => attr.Name == attributeName)).FirstOrDefault();
 return element == null ? string.Empty : element.Value;
 }

public static Entity GetGlobalTemplate(string title, IOrganizationService orgService)
 {
 Entity emailTemplate = null;
 try
 {

QueryExpression query = new QueryExpression();

// Setup the query for the template entity
 query.EntityName = "template";

// Return all columns
 query.ColumnSet.AllColumns = true;
 query.Criteria = new FilterExpression();
 query.Criteria.FilterOperator = LogicalOperator.And;

// Create the title condition
 ConditionExpression condition1 = new ConditionExpression();
 condition1.AttributeName = "title";
 condition1.Operator = ConditionOperator.Equal;
 condition1.Values.Add(title);

query.Criteria.Conditions.Add(condition1);

// Execute the query and return the result
 EntityCollection entityColl = orgService.RetrieveMultiple(query);

if (entityColl.Entities.Count > 0)
 {
 emailTemplate = entityColl.Entities[0];
 }
 }
 catch
 {
 throw;
 }
 return emailTemplate;
 }

The email activity created :-

Bye.


Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

4 thoughts on “Sample code to use Template’s content while sending mail using SendEmailReuquest in CRM 2011”

  1. How to get datafields value used in email template’s body and subject? Is there any way out there to do it?

    And, thank you for this article.

    Like

    1. Hi Madhu,
      List fromtoEntities = new List();

      Entity activityParty = new Entity();
      activityParty.LogicalName = “activityparty”;
      activityParty.Attributes[“partyid”] = new EntityReference(“systemuser”, new Guid(“FC480E73-77A9-E111-B151-00155D882D40”));

      fromtoEntities.Add(activityParty);

      Here in the above code create as many activityParty records and add them to fromtoEntities list as to whom you want to send the mail.

      Like

Share your thoughts

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