web
You’re offline. This is a read only version of the page.
close
Skip to main content
Community site session details

Community site session details

Session Id :
Microsoft Dynamics 365 | Integration, Dataverse...
Unanswered

Cannot insert duplicate key plugin send email in dynamics 365 CRM

(0) ShareShare
ReportReport
Posted on by 2,745 User Group Leader

Hi Experts,

I am trying to send email to all required attendees and optional attendees of an appointment using plugin. It works fine on CREATE message but in update message its throwing error as Duplicate key cannot insert.

here is my code.

using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using System;

namespace Send_Email_Plugin
{
// Importnant Note-------------------------------------------------------------------------------------------------------------------
// When you are sending emails you have to go to User profile in CRM from which the email gets triggered, and click on "APPROVE EMAIL"
// The Email Box should configured properly.
//-----------------------------------------------------------------------------------------------------------------------------------
public class SendEmail_Plugin : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
//Tracing Object
ITracingService tracing = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

//ExecutionContext Object
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

//OrganizationServiceFactory Object
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

//OrganizationService Object
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

string functionName = "Execute";

try
{
EntityCollection requiredAttendees;
EntityCollection optionalAttendees;
EntityReference RegardingEntRef;
Entity appointmentEn;

if (context.MessageName == "Update")
appointmentEn = context != null && context.InputParameters.Contains("Target") ? (Entity)context.PostEntityImages["PostImage"] : null;
else if (context.MessageName == "Create")
appointmentEn = context != null && context.InputParameters.Contains("Target") ? (Entity)context.InputParameters["Target"] : null;
else
return;

tracing.Trace("retrieved entity :" + appointmentEn.LogicalName + "Message:" + context.MessageName);

if (appointmentEn.LogicalName == "appointment")
{
tracing.Trace("validated entity..");
if (appointmentEn.Attributes.Contains("requiredattendees") && appointmentEn.Attributes.Contains("optionalattendees") && appointmentEn.Attributes.Contains("regardingobjectid"))
{
tracing.Trace("Validated attendees");

//read regarding field
RegardingEntRef = appointmentEn.GetAttributeValue<EntityReference>("regardingobjectid");
tracing.Trace("regarding : " + RegardingEntRef.Name);

//read required and optional attendees
requiredAttendees = appointmentEn.Attributes.Contains("requiredattendees") ? appointmentEn.GetAttributeValue<EntityCollection>("requiredattendees") : null;
optionalAttendees = appointmentEn.Attributes.Contains("optionalattendees") ? appointmentEn.GetAttributeValue<EntityCollection>("optionalattendees") : null;
var appointmentSubject = appointmentEn.Attributes.Contains("subject") ? appointmentEn.GetAttributeValue<String>("subject") : null;
var appointmentLocation = appointmentEn.Attributes.Contains("location") ? appointmentEn.GetAttributeValue<String>("location") : null;
var appointdescription = appointmentEn.Attributes.Contains("description") ? appointmentEn.GetAttributeValue<String>("description") : null;

//send email to required attendees
if (requiredAttendees != null && requiredAttendees.Entities.Count > 0)
{
SendEmail(requiredAttendees, appointmentSubject, appointdescription, service, tracing);
}

//send email to optional attendees
if (optionalAttendees != null && optionalAttendees.Entities.Count > 0)
{
SendEmail(requiredAttendees, appointmentSubject, appointdescription, service, tracing);
}
}
}
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException(functionName + ": " + ex.Message);
}
}
public void SendEmail(EntityCollection ec, string subject, string desc, IOrganizationService svc,ITracingService trace)
{
trace.Trace("inside SendEmail EC");
// Create a new EntityCollection and add the all parties
EntityCollection to = new EntityCollection();
foreach (var attendees in ec.Entities)
{
to.Entities.Add(attendees);
}
trace.Trace("after EC");

// Create an email with the EntityCollection
Entity email = new Entity("email");
email["subject"] = subject;
email["to"] = to;
email["description"] = desc;
var eid = svc.Create(email);

trace.Trace("after email create");
SendEmailRequest sendEmailReq = new SendEmailRequest
{
EmailId = eid,
TrackingToken = "",
IssueSend = true
};
SendEmailResponse sendEmailResp = (SendEmailResponse)svc.Execute(sendEmailReq);
trace.Trace("after email sent");
}
}
}

I have the same question (0)
  • erhan.keskin Profile Picture
    2,253 on at
    RE: Cannot insert duplicate key plugin send email in dynamics 365 CRM

    Hi Sanjaya,

    You shouldn't use entities from requiredAttendees directly, you need to create your new activity parties for the email, and get party ids from it. Does it make sense?

    regards,

    Erhan

  • Sanjaya Prakash Pradhan Profile Picture
    2,745 User Group Leader on at
    RE: Cannot insert duplicate key plugin send email in dynamics 365 CRM

    As per the requirement I have achieved this using a workflow which is out of the box workflow so no coding is required.

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

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Microsoft Dynamics 365 | Integration, Dataverse, and general topics

#1
#ManoVerse Profile Picture

#ManoVerse 107

#2
Siv Sagar Profile Picture

Siv Sagar 93 Super User 2025 Season 2

#3
Martin Dráb Profile Picture

Martin Dráb 69 Most Valuable Professional

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans