Thursday 2 February 2012

Sending Email from xRM/CRM plugin


// Here toList contains both system user and contact references

public static void SendEmail(IOrganizationService crmService, EntityReference from, List<EntityReference> toList, string subject, string body)
        {
            Entity fromParty = new Entity("activityparty");
            fromParty["partyid"] = from;

            Entity[] toPartyArray = new Entity[toList.Count];

            for (int i = 0; i < toList.Count; i++)
            {
                Entity toParty = new Entity("activityparty");
                toParty["partyid"] = toList[i];

                toPartyArray[i] = toParty;
            }

            Entity email = new Entity("email");
            email["from"] = new Entity[] { fromParty };
            email["to"] = toPartyArray;

            email["subject"] = subject;
            email["description"] = body;

            Guid emailId = crmService.Create(email);

            OrganizationRequest emailRequest = new OrganizationRequest("SendEmail");
            emailRequest.Parameters.Add("EmailId", emailId);
            emailRequest.Parameters.Add("IssueSend", true);
            emailRequest.Parameters.Add("TrackingToken", string.Empty);
            crmService.Execute(emailRequest);
        }


http://rajeevpentyala.wordpress.com/2011/08/03/sending-an-email-using-crm-2011-plug-in/

http://blogs.infinite-x.net/2006/12/04/sendemailrequesttrackingtoken-field-documentation-error/


When sending an email on change of ownership of record, I was getting error "some error occurred", to resolved it set the caller id "on behalf of" as below


            EntityReference callingUser = new EntityReference
            {
                LogicalName = "systemuser",
                Id = localContext.PluginExecutionContext.InitiatingUserId
            };

            OrganizationServiceProxy serviceProxy = (OrganizationServiceProxy)crmService;
            serviceProxy.CallerId = callingUser.Id;




2 comments:

  1. Hi, thanks for this & other great posts on your blog

    You can read my article about sending email from CRM plugin
    http://ekoncis.blogspot.com/2012/01/crm-2011-custom-email-with-pdf-report.html

    ReplyDelete