Skip to main content

Notifications

Microsoft Dynamics CRM (Archived)

c# replace email template

Posted on by 2,397

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

  • Suggested answer
    Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: c# replace email template

    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

  • Aric Levin Profile Picture
    Aric Levin 30,188 on at
    RE: c# replace email template

    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.

  • sdnd2000 Profile Picture
    sdnd2000 2,397 on at
    RE: c# replace email template

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

  • Suggested answer
    Nithya Gopinath Profile Picture
    Nithya Gopinath 17,074 on at
    RE: c# replace email template

    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.

  • Suggested answer
    Aric Levin Profile Picture
    Aric Levin 30,188 on at
    RE: c# replace email template

    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...

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

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Community AMA December 12th

Join us as we continue to demystify the Dynamics 365 Contact Center

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,240 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,149 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans