web
You’re offline. This is a read only version of the page.
close
Skip to main content

Announcements

No record found.

News and Announcements icon
Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

c# replace email template

(0) ShareShare
ReportReport
Posted on by 2,512

Hi, I am trying to send out email with template, but how can I modify the template body text, and then send out, here is my code,

Email email = new Email
                    {
                        To = new ActivityParty[] { toParty },
                        From = new ActivityParty[] { fromParty },
                        Subject = "SDK Sample e-mail",
                        Description = "SDK Sample for SendEmailFromTemplate Message.",
                        DirectionCode = true
                    };



QueryExpression queryBuildInTemplates = new QueryExpression{
                        EntityName = "template",
                        ColumnSet = new ColumnSet(true),
                        Criteria = new FilterExpression()
                    };
                    queryBuildInTemplates.Criteria.AddCondition("title",
                        ConditionOperator.Equal, "test");
                    EntityCollection templateEntityCollection = _serviceProxy.RetrieveMultiple(queryBuildInTemplates);

                    if (templateEntityCollection.Entities.Count > 0) 
                    {
                        _templateId = (Guid)templateEntityCollection.Entities[0].Attributes["templateid"];
                    }
                    else
                    {
                        throw new ArgumentException("Standard Email Templates are missing");
                    }             

                    // Create the request
                    SendEmailFromTemplateRequest emailUsingTemplateReq = new SendEmailFromTemplateRequest
                    {
                        Target = email,

                        // Use a built-in Email Template of type "contact".
                        TemplateId = _templateId,

                        // The regarding Id is required, and must be of the same type as the Email Template.
                        RegardingId = _contactId,
                        RegardingType = Contact.EntityLogicalName
                    };

                    SendEmailFromTemplateResponse emailUsingTemplateResp = (SendEmailFromTemplateResponse)_serviceProxy.Execute(emailUsingTemplateReq);


*This post is locked for comments

I have the same question (0)
  • Suggested answer
    Aric Levin - MVP Profile Picture
    30,190 Moderator on at

    The following worked for me:

    Entity template = service.Retrieve("template", templateId, new ColumnSet(true));

    subject = GetDataFromXml(template.Attributes["subject"].ToString(), "match");

    string body = GetDataFromXml(template.Attributes["body"].ToString(), "match");

    description = UpdateDescription(body, findText, replaceWith);

           private 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;

           }

           // Modify this to fit your needs

           private string UpdateDescription(string description, sourceText, targetText)

           {

               StringBuilder sb = new StringBuilder();

               string[] lines = description.Split('\n');

               foreach (string line in lines)

               {

                  sb.AppendLine(line);

               }

               return sb.ToString();

           }

    Hope this helps...

  • Suggested answer
    Nithya Gopinath Profile Picture
    17,078 on at

    Hi,

    Please go through the code in the following link.

    nishantrana.me/.../sample-code-to-use-templates-content-while-sending-mail-using-sendemailreuquest-in-crm-2011

    Hope this helps.

  • sdnd2000 Profile Picture
    2,512 on at

    Thanks for the help. Is there anyway that we can verify that the email has been sent?

  • Aric Levin - MVP Profile Picture
    30,190 Moderator on at

    The process might complete before the email actually is sent (might still be in Pending Send Status or other status).

    You would have to run a separate process to check if you have unsent mails (such as Action, Workflow or custom application).

    Is you source above inside a plugin or is it separate from the application (console).

    If it's separate, you can query the email message and check for the Status Reason of the Email. If the Status Reason is 3 (Sent), then it has been sent.

    Check out the different status reasons here:

    technet.microsoft.com/.../dn531157.aspx

    Hope this helps.

  • Suggested answer
    Community Member Profile Picture
    on at

    Hi sdnd2000,

    you could delegate email send to a workflow, then if you need to check workflow status directly into c# code you could proceed with the following code:

    ExecuteWorkflowRequest request = new ExecuteWorkflowRequest()
    {
    	WorkflowId = workflowId,
    	EntityId = entityId
    };
    
    ExecuteWorkflowResponse response = (ExecuteWorkflowResponse)crmService.Execute(request);
    
    for (int i = 0; i < waitForSeconds; i++)
    {
    	System.Threading.Thread.Sleep(1000);
    
    	List<Entity> asyncoperationentlist = EntityCrm.RetrieveList(crmService, "asyncoperation", "stateCode", "asyncoperationid", response);
    
    	if (asyncoperationentlist.Count > 0)
    	{
    		foreach (Entity asyncoperationent in asyncoperationentlist)
    		{
    			if (asyncoperationent.GetAttributeValue<OptionSetValue>("stateCode").Value == (int)Enums.AsyncOperationState.Completed)
    				// do something
    			etc ...
    		}
    	}
    }

    Hope it helps!

    If you found the answer helpful, please mark as Verified 

    Join my network on LinkedIn      Follow me on Twitter 

    Thank You & Best Regards

    Francesco Picchi

    Microsoft Dynamics CRM Consultant, Bologna+Milano, ITALY

    Independent Contractor

    http://www.francescopicchi.com

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Introducing the 2026 Season 1 community Super Users

Congratulations to our 2026 Super Stars!

Meet the Microsoft Dynamics 365 Contact Center Champions

We are thrilled to have these Champions in our Community!

Congratulations to the April Top 10 Community Leaders

These are the community rock stars!

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans