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 using 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 sent email, we can use SentEmailRequest to sent the email:

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

If you only want to create email with status sent but not actually trigger your email router to sending email, you can set IssueSend = false. But if you want to trigger your email router to sending 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 triggering email router).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.