Dynamics CRM Sent Email using Plugin

I had one requirement to send an email daily for every case that was created and still in the stage of investigation/re-investigation state. Before this customization is used in workflow but somehow the performance is not too good and I change it into the plugin.

Create Email Entity

There is no special code when we want to create an email entity:

// Create a contact to send an email to (To: field)
var emailContact = new Contact
{
FirstName = "Nancy",
LastName = "Anderson",
EMailAddress1 = "nancy@contoso.com"
};
var contactId = service.Create(emailContact);

// Get a system user to send the email (From: field)
var systemUserRequest = new WhoAmIRequest();
var systemUserResponse = (WhoAmIResponse)service.Execute(systemUserRequest);
var userId = systemUserResponse.UserId;

// Create the 'From:' activity party for the email
var fromParty = new ActivityParty
{
PartyId = new EntityReference(SystemUser.EntityLogicalName, userId)
};

// Create the 'To:' activity party for the email
var toParty = new ActivityParty
{
PartyId = new EntityReference(Contact.EntityLogicalName, contactId)
};
// Create an e-mail message.
var email = new Email
{
To = new ActivityParty[] { toParty },
From = new ActivityParty[] { fromParty },
Subject = "SDK Sample e-mail",
Description = "SDK Sample for SendEmail Message.",
DirectionCode = true
};
var emailId = service.Create(email);

Sent Email Request

When we want to send an email, we can use SentEmailRequest to send the email:

var sendEmailreq = new SendEmailRequest
{
EmailId = emailId,
TrackingToken = "",
IssueSend = true
};

If you only want to create an email with the status sent but do not actually trigger your email router to send email, you can set IssueSend = false. But if you want to trigger your email router to send the email, you must put IssueSend = true because the default value for this one is false (will only make your email status sent but not trigger the email router).

Leave a comment

Your comment is sent privately to the author and isn't published on the site.