Send Email (User / Team) While Sharing Record CRM 2011


Hi all,

Recently i had a requirement  to create Email While sharing a record to an team / User , we need to create and send email to (User / Team) to whom the Record has been shared. It z an OOB Function.

  • Capture Record ID  for which we are going to share.
  • Check weather Shared record to User or Team.
  • If the record has been shared to User means set the  User  in  To field in Email .
  • If  the record has been shared to Team means Retrieve list of user belongs to the Team and place them in  To field in Email .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Crm.Sdk.Messages;
using xrm;

namespace ShareRecordEmail
{
    public class EmailTOSharedRecord: IPlugin
    {

        public void Execute(IServiceProvider serviceProvider)
        {
            // Obtain the execution context from the service provider.
            Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)
            serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));

            // Obtain the organization service reference.
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

            // The InputParameters collection contains all the data passed in the message request.
            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is EntityReference)
            {

                // Entity Record To be shared
                EntityReference Account = ((EntityReference)context.InputParameters["Target"]);

                // User or Team  for whom the record has been shared
                EntityReference sharedRecord = ((PrincipalAccess)context.InputParameters["PrincipalAccess"]).Principal;

                if (sharedRecord.LogicalName == "user")
                {

                    // System User ID who has shared the record
                    Guid fromUserId = context.UserId;
                    // Send An EMail
                    EmailUser(service, sharedRecord, fromUserId, Account);
                }

                else if (sharedRecord.LogicalName == "team")
                {

                    //Creating XRM  Service Context
                    XrmServiceContext datacontext = new XrmServiceContext(service);

                    // Retrieving List of Users in the Team

                    List teamMembers = (from t in datacontext.TeamMembershipSet where t.TeamId == sharedRecord.Id select t).ToList();

                    TeamEmail(service, teamMembers, context.UserId, sharedRecord);

                }
            }

        }

        private void EmailUser(IOrganizationService service, EntityReference sysUser, Guid fromUserId, EntityReference regarding)
        {
            Entity email = new Entity("email");
            email.Attributes.Add("subject", "New Account Has been Shared With You");
            email.Attributes.Add("description", "
" + "A new Account has recieved.  " + "
" + "Please to view the Account shared with you " + "
");
            email.Attributes.Add("regardingobjectid", regarding);

            EntityReference from = new EntityReference("systemuser", fromUserId);
            EntityReference to = sysUser;

            Entity fromParty = new Entity("activityparty");
            fromParty.Attributes.Add("partyid", from);
            Entity toParty = new Entity("activityparty");
            toParty.Attributes.Add("partyid", to);

            EntityCollection frmPartyCln = new EntityCollection();
            frmPartyCln.EntityName = "systemuser";
            frmPartyCln.Entities.Add(fromParty);

            EntityCollection toPartyCln = new EntityCollection();
            toPartyCln.EntityName = "systemuser";
            toPartyCln.Entities.Add(toParty);

            email.Attributes.Add("from", frmPartyCln);
            email.Attributes.Add("to", toPartyCln);

            //Create an EMail Record
            Guid _emailId = service.Create(email);

            // Use the SendEmail message to send an e-mail message.
            SendEmailRequest sendEmailreq = new SendEmailRequest
            {
                EmailId = _emailId,
                TrackingToken = "",
                IssueSend = true
            };

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

        private void TeamEmail(IOrganizationService service, List teamMembers, Guid fromUserId, EntityReference regarding)
        {

            Email email = new Email();

            email.Subject = "New Account Has been Shared With You";

            email.Description = "
" + "Dear Team  " + "
" + "Please Go through the Account shared with you " + "
";

            // Set the from user of the email to Logged in user
            ActivityParty fromParty = new ActivityParty();
            fromParty.PartyId = new EntityReference(SystemUser.EntityLogicalName, fromUserId);

            List toPartyList = new List();

            // Add the Activity party for each member in the team
            foreach (TeamMembership user in teamMembers)
            {
                ActivityParty toParty = new ActivityParty();
                toParty.PartyId = new EntityReference(SystemUser.EntityLogicalName, user.SystemUserId.Value);
                toPartyList.Add(toParty);
            }

            // Add To and From users to email
            email.To = toPartyList.ToArray();
            //  email.To = toPartyList.ToArray();
            email.From = new[] { fromParty };

            // Set the Account regarding
            email.RegardingObjectId = new EntityReference(Account.EntityLogicalName, regarding.Id);

            // Email GUID
            Guid emailId = service.Create(email);

            // Use the SendEmail message to send an e-mail message.
            SendEmailRequest sendEmailreq = new SendEmailRequest
            {
                EmailId = emailId,
                TrackingToken = "",
                IssueSend = true
            };

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

        }

    }
}

  • Register your plugin Message = GrantAccess
    • Primary Entity = account
    • Post OperationEmail