Sample code to send a simple email connected to an Incident entity:
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Tooling.Connector;
using System;
using System.Configuration;
using Xrm;
namespace CrmDevelopersHowTo
{
public static class SendEmailSamples
{
public static void SendSimpleEmail()
{
// Initiate CRM-connection
var conn = new CrmServiceClient(ConfigurationManager.ConnectionStrings["CONN"].ConnectionString);
var service = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;
Guid regardingObjectGuid = new Guid("----- Incident Id -----"); //Example - could be a lot of other entity types
EntityReference regardingObjectRef = new EntityReference("incident", regardingObjectGuid);
Guid senderGuid = new Guid("----- System User Id -----");
EntityReference senderRef = new EntityReference("systemuser", senderGuid);
ActivityParty fromParty = new ActivityParty()
{
PartyId = senderRef
};
Guid recipientGuid = new Guid("----- Contact Id -----");
EntityReference recipientRef = new EntityReference("contact", recipientGuid);
ActivityParty toParty = new ActivityParty()
{
PartyId = recipientRef
};
Email email = new Email()
{
From = new ActivityParty[] { fromParty },
To = new ActivityParty[] { toParty },
Subject = "Email test",
Description = "<div>This is an email test!</div>",
RegardingObjectId = regardingObjectRef,
DirectionCode = true //Sets the direction to "Outgoing"
};
Guid emailId = service.Create(email);
SendEmailRequest req = new SendEmailRequest()
{
EmailId = emailId,
TrackingToken = "",
IssueSend = true
};
//Send the email
SendEmailResponse res = (SendEmailResponse)service.Execute(req);
}
}
}
Once the email has been sent, it should be visible as an email activity in the selected incident entity’s timeline.
Observe: The sample supplied requires early bound entity classes for ActivityParty, Email, SendEmailRequest and SendEmailResponse!