Dear Dynamics People,
I receive one requirement,that is send email with dynamics data gird in HTML format.But by default Dynamics CRM not provide this type of feature. Dynamic provide the mail merge option but that is not match with my requirement.
In this post we check how we can send dynamic data in email body with HTML format via Custom WorkFlow.
- Make two input argument for sender and receiver
- Get records guid {In my case, all required GUID in text box using java script }
- Design HTML table tag as per requirement
- Convert HTML string to Base
- Create email activity
- Add attributes subject,from,to,email body
A code is below.
public class SendDynamicHTMLLetter : CodeActivity { [Input("Sender")] [ReferenceTarget("systemuser")] public InArgument<EntityReference> Sender { get; set; } [Input("Reciever")] [ReferenceTarget("queue")] public InArgument<EntityReference> Reciever { get; set; } IOrganizationService service; protected override void Execute(CodeActivityContext executionContext) { try { string TypeL = null; string guidArray = null; string[] guidList; char[] commaSeparator = new char[] { ',' }; Guid reciever = Guid.Empty; Guid sender = Guid.Empty; string emailBody = null; // Get context IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>(); //Create service factory object IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>(); ITracingService tracingService = executionContext.GetExtension<ITracingService>(); // Create Organization service service = serviceFactory.CreateOrganizationService(context.UserId); if (context.Depth <= 1) { //Retrieve the GUIDs of records {In my case all guids store in textbox with comma separated Entity emailObj = (Entity)service.Retrieve("new_sendemail", context.PrimaryEntityId, new ColumnSet(true)); TypeL = Convert.ToString(emailObj.Attributes["new_type"]); guidArray = Convert.ToString(emailObj.Attributes["new_array"]); guidList = guidArray.Split(commaSeparator, StringSplitOptions.None); if (TypeL.Equals("Mandatory")) { //Get HTML Body emailBody = HtlmMandatory(TypeL, guidList); } else if (TypeL.Equals("Announcement")) { emailBody = HtlmAnnouncement(TypeL, guidList); } //Set reciever reciever = Reciever.Get<EntityReference>(executionContext).Id; //Set Sender sender = Sender.Get<EntityReference>(executionContext).Id; //Send Email Function SendMail(reciever, sender, emailBody, service, context.PrimaryEntityId, TypeL); } } catch(Exception ex) { throw new Exception(" error in SendEmail " + ex.Message); } } //Create HTML Body</pre> public string HtlmMandatory(string Lettertype, string[] guidList) { //Desgin HTML Table tags StringBuilder messageBody = new StringBuilder(); string htmltop = "<P> Dear Abhi,</br> Kindly issue " + Lettertype + " Letter for those list.</P></div>"; string htmlTableStart = "<table style=\"border-collapse:collapse; text-align:center;\" >"; string htmlTableEnd = "</table>"; string htmlHeaderRowStart = "<tr style=\"background-color:#6FA1D2; color:#ffffff;\">"; string htmlHeaderRowEnd = "</tr>"; string htmlTrStart = "<tr style=\"color:#555555;\">"; string htmlTrEnd = "</tr>"; string htmlTdStart = "<td style=\" border-color:#5c87b2; border-style:solid; border-width:thin; padding: 5px;\">"; string htmlTdEnd = "</td>"; string ProviderCode = null; string ProviderName = null; string ContactName = null; string ContactNumber = null; string JobTitle = null; string EmailAddress = null; string VendorName = null; string emailBody = null; //Create HTML table header messageBody.Append(htmltop); messageBody.Append(htmlTableStart); messageBody.Append(htmlHeaderRowStart); messageBody.Append(htmlTdStart + "SNo." + htmlTdEnd); messageBody.Append(htmlTdStart + "Provider Code" + htmlTdEnd); messageBody.Append(htmlTdStart + "Provider Name" + htmlTdEnd); messageBody.Append(htmlTdStart + "Contact Name" + htmlTdEnd); messageBody.Append(htmlTdStart + "Contact Number" + htmlTdEnd); messageBody.Append(htmlTdStart + "Job Title" + htmlTdEnd); messageBody.Append(htmlTdStart + "Email Address" + htmlTdEnd); messageBody.Append(htmlTdStart + "Vendor Name" + htmlTdEnd); messageBody.Append(htmlHeaderRowEnd); int count = 0; //Fetch required Dynamic Data for rows for (int i = 0; i <= guidList.Length - 1; i++) { Guid guid = new Guid(guidList[i]); Entity LetterObj = (Entity)service.Retrieve("new_mandatoryannouncement", guid, new ColumnSet(true)); if (LetterObj.Contains("new_providercode")) { EntityReference ProviderCode_ = (EntityReference)(LetterObj.Attributes["new_providercode"]); ProviderCode = ProviderCode_.Name; } if (LetterObj.Contains("new_providername")) { ProviderName = Convert.ToString(LetterObj.Attributes["new_providername"]); } if (LetterObj.Contains("new_contactname")) { ContactName = Convert.ToString(LetterObj.Attributes["new_contactname"]); } if (LetterObj.Contains("new_contactnumber")) { ContactNumber = Convert.ToString(LetterObj.Attributes["new_contactnumber"]); } if ((LetterObj.Contains("new_jobtitle"))) { JobTitle = Convert.ToString(LetterObj.Attributes["new_jobtitle"]); } if (LetterObj.Contains("new_emailaddress")) { (LetterObj.Attributes["new_emailaddress"])).Name; EmailAddress = Convert.ToString(LetterObj.Attributes["new_emailaddress"]); } if (LetterObj.Contains("new_vendorname")) { EntityReference VendorName_ = (EntityReference)LetterObj.Attributes["new_vendorname"]; //Convert.ToString(LetterObj.Attributes["new_vendorname"]); VendorName = VendorName_.Name; } count++; //Create HTML Table rows with Dynamic Data messageBody.Append(htmlTrStart); messageBody.Append(htmlTdStart + count + htmlTdEnd); messageBody.Append(htmlTdStart + ProviderCode + htmlTdEnd); messageBody.Append(htmlTdStart + ProviderName + htmlTdEnd); messageBody.Append(htmlTdStart + ContactName + htmlTdEnd); messageBody.Append(htmlTdStart + ContactNumber + htmlTdEnd); messageBody.Append(htmlTdStart + JobTitle + htmlTdEnd); messageBody.Append(htmlTdStart + EmailAddress + htmlTdEnd); messageBody.Append(htmlTdStart + VendorName + htmlTdEnd); messageBody.Append(htmlTrEnd); } messageBody.Append(htmlTableEnd); messageBody.Append("<p><br>Regards,</p></div></body></html>"); emailBody = messageBody.ToString(); return emailBody; } //Send Email private void SendMail(Guid reciever, Guid sender, string emailBody, IOrganizationService service, Guid guid,string sub) { try { Entity email = new Entity("email"); //Set To EntityReference to = new EntityReference("queue", reciever); //Set From EntityReference from = new EntityReference("systemuser", sender); EntityReference Regarding = new EntityReference("new_sendemail", guid); //Derive from party Entity fromParty = new Entity("activityparty"); fromParty.Attributes.Add("partyid", from); //Derive to party Entity toParty = new Entity("activityparty"); toParty.Attributes.Add("partyid", to); EntityCollection collFromParty = new EntityCollection(); collFromParty.EntityName = "systemuser"; collFromParty.Entities.Add(fromParty); EntityCollection collToParty = new EntityCollection(); collToParty.EntityName = "queue"; collToParty.Entities.Add(toParty); email.Attributes.Add("from", collFromParty); email.Attributes.Add("to", collToParty); //Defining Activity Parties (ends) //Set subject & body properties email.Attributes.Add("subject", "Request for " + sub + " letter"); email.Attributes.Add("description", emailBody); email["regardingobjectid"] = new EntityReference("new_sendemail", guid); //Create email activity Guid emailID = service.Create(email); string base64str = ""; //Convert string to base64string base64str = getPDFDocumentString(emailBody); int NextActorID = new int(); RetrieveEntityRequest request = new RetrieveEntityRequest(); request.LogicalName = "email"; RetrieveEntityResponse response = (RetrieveEntityResponse)service.Execute(request); int objecttypecode = response.EntityMetadata.ObjectTypeCode.Value; //Add require parameter of Email Entity attachment = new Entity("activitymimeattachment"); attachment.Attributes.Add("subject", "Report"); attachment.Attributes.Add("filename", "Job Report.pdf"); //HTML Table as Email Body attachment.Attributes.Add("body", base64str); attachment.Attributes.Add("filesize", Convert.ToInt32(base64str.Length.ToString())); attachment.Attributes.Add("mimetype", "text/plain"); attachment.Attributes.Add("attachmentnumber", NextActorID); attachment.Attributes.Add("objectid", new EntityReference("email", emailID)); attachment.Attributes.Add("objecttypecode", objecttypecode); service.Create(attachment); //Create the attachment //Sending email SendEmailRequest reqSendEmail = new SendEmailRequest(); reqSendEmail.EmailId = emailID; //ID of created mail reqSendEmail.TrackingToken = string.Empty; reqSendEmail.IssueSend = true; SendEmailResponse res = (SendEmailResponse)service.Execute(reqSendEmail); } catch (Exception ex) { throw new Exception(" error in SendEmail " + ex.Message); } } //Convert String to base64string public string getPDFDocumentString(string emailBody) { string base64str = ""; using (MemoryStream memoryStream = new MemoryStream()) { Document document = new Document(); PdfWriter.GetInstance(document, memoryStream); document.Open(); Paragraph para = new Paragraph(emailBody); document.Add(para); document.Close(); base64str = Convert.ToBase64String(memoryStream.ToArray()); return base64str; } }
Email Activity
Thank you!!!
*This post is locked for comments