Friday, 22 December 2023

Send Email from Microsoft Dynamics CRM

 Below is the code reg how to send Email from D365 CRM using C# : 


  Entity email = new Entity("email");


        if (!string.IsNullOrEmpty(To))

        {

            EntityCollection toCollect = new EntityCollection();

            var partylist = NATo.Split(';');

            if (partylist.Length > 0)

            {

                foreach (var partys in partylist)

                {

                    if (!string.IsNullOrEmpty(partys))

                    {

                        Entity toparty = new Entity("activityparty");

                        toparty["addressused"] = partys;

                        toCollect.Entities.Add(toparty);

                    }

                }

            }

            else if (!string.IsNullOrEmpty(To))

            {

                Entity toparty = new Entity("activityparty");

                toparty["addressused"] = To;

                toCollect.Entities.Add(toparty);

            }


            email["to"] = toCollect;

        }


        string fetchportalconfigutaions = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>

                              <entity name='portalconfiguration'>

                                <all-attributes />

                                <filter type='and'>

                                  <condition attribute='name' operator='eq' value='SEND_EMAIL_ID'/>

                                </filter>

                              </entity>

                            </fetch>";

        EntityCollection emailfrom = service.RetrieveMultiple(new FetchExpression(fetchportalconfigutaions));

        string strEntityName = string.Empty, strRecordID = string.Empty;

        Guid FromID = Guid.Empty;

        if (emailfrom.Entities.Count > 0)

        {

            if (emailfrom[0].Attributes.Contains("NA_configurationkey"))

                strEntityName = emailfrom[0].Attributes["NA_configurationkey"].ToString();

            if (emailfrom[0].Attributes.Contains("NA_configurationvalue"))

                strRecordID = emailfrom[0].Attributes["NA_configurationvalue"].ToString();

        }


        Entity Fromparty = new Entity("activityparty");

        if (!string.IsNullOrEmpty(strEntityName) && !string.IsNullOrEmpty(strRecordID) && Guid.TryParse(strRecordID, out FromID))

            Fromparty["partyid"] = new EntityReference(strEntityName, FromID);

        else

        {

            Fromparty["partyid"] = new EntityReference("systemuser", new Guid("638A9F0A-DFB2-E711-A824-000D3AA32A16"));

        }


        email["from"] = new Entity[] { Fromparty };

        email["subject"] = subject;


        if (string.IsNullOrWhiteSpace(bodyxml) || string.IsNullOrEmpty(bodyxml))

        {

            email["description"] = bodyHTML;

        }

        else if (!string.IsNullOrEmpty(bodyxml) || !string.IsNullOrWhiteSpace(bodyxml))

        {

            email["description"] = bodyxml;

        }


        email["directioncode"] = true;

        email["regardingobjectid"] = PostImage.ToEntityReference();


        Guid emailId = service.Create(email);


        if (emailId != null && emailId != Guid.Empty)

        {

            tracingService.Trace("Email Activity Created. ID:-" + Convert.ToString(emailId));


            tracingService.Trace("Wait 5 Seconds before adding attahment");

            System.Threading.Thread.Sleep(new TimeSpan(0, 0, 5));

            tracingService.Trace("Continuing :  Adding attahment");

            QueryExpression queryNotes = new QueryExpression("annotation");

            queryNotes.ColumnSet = new ColumnSet(new string[] { "subject", "mimetype", "filename", "documentbody" });

            queryNotes.Criteria = new FilterExpression();

            queryNotes.Criteria.FilterOperator = LogicalOperator.And;

            queryNotes.Criteria.AddCondition(new ConditionExpression("objectid", ConditionOperator.Equal, PostImage.ToEntityReference().Id));

            EntityCollection mimeCollection = service.RetrieveMultiple(queryNotes);

            foreach (var attachment in mimeCollection.Entities)

            {

                Entity emailAttachment = new Entity("activitymimeattachment");

                if (attachment.Contains("subject")) emailAttachment["subject"] = attachment["subject"];

                if (attachment.Contains("filename")) emailAttachment["filename"] = attachment["filename"];

                if (attachment.Contains("documentbody")) emailAttachment["body"] = attachment["documentbody"];

                if (attachment.Contains("mimetype")) emailAttachment["mimetype"] = attachment["mimetype"];

                emailAttachment["objectid"] = new EntityReference("email", emailId);

                emailAttachment["objecttypecode"] = "email";

                service.Create(emailAttachment);

                tracingService.Trace("Email Attachment Added.");

            }


            SendEmailRequest sendEmailreq = new SendEmailRequest

            {

                EmailId = emailId,

                IssueSend = true

            };


            SendEmailResponse sendEmailresp = (SendEmailResponse)service.Execute(sendEmailreq);

        }

No comments:

Post a Comment