MS Dynamics 365 - Create an email activity using dynamics crm Rest API - C#

Ankaprasad
Posted by Ankaprasad under C# category on | Points: 40 | Views : 1391
Prerequisites:

Please refer the below link, to understand how to get azure auth token/ Access token.

https://ankaprasad.wordpress.com/2020/01/08/consume-ms-dynamics-crm-web-api-using-azure-ad-auth-token/

Create email activity in CRM

        CreateEmailActivity("ef9b833b-0000-0000-0000-000000000000", authToken)

        public static void CreateEmailActivity(string recordId, string accessToken)
{
JObject email = new JObject();

email["subject"] = "Email Subject";
email["description"] = "This is email body";
email["regardingobjectid_incident@odata.bind"] = "/incidents(" + recordId + ")";

JArray parties = new JArray();

JObject from = new JObject();
from["partyid_systemuser@odata.bind"] = "/systemusers(00000000-0000-0000-0000-000000000000)";
from["participationtypemask"] = 1; // From Email
parties.Add(from);

// Send Email to CRM Contact
JObject toContact = new JObject();
toContact["partyid_contact@odata.bind"] = "/contacts(00000000-0000-0000-0000-000000000000)";
toContact["participationtypemask"] = 2; // To Email
parties.Add(toContact);

// Send Email to email which is not present in CRM
JObject to = new JObject();
to["addressused"] = "XXXXXX@gmail.com";
to["participationtypemask"] = 2; // To Email
parties.Add(to);

email["email_activity_parties"] = parties;

string emailUrl = Task.Run(async () => await CreateRecord(accessToken, "emails", email)).Result;

}

        public static async Task<string> CreateRecord(string accesToken, string entityName, JObject entityObject)
{

string apiUrl = "https://xyka12.api.crm8.dynamics.com/api/data/v9.1/";
string recordUri = "";
HttpClient client = new HttpClient();
client.Timeout = TimeSpan.FromSeconds(360);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accesToken);
client.BaseAddress = new Uri(apiUrl);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
client.DefaultRequestHeaders.Add("OData-Version", "4.0");
client.DefaultRequestHeaders.Add("Cache-Control", "no-cache");

HttpRequestMessage createHttpRequest = new HttpRequestMessage(HttpMethod.Post, apiUrl + entityName);
createHttpRequest.Content = new StringContent(entityObject.ToString(), Encoding.UTF8, "application/json");
var response = await client.SendAsync(createHttpRequest);
response.EnsureSuccessStatusCode();

if (response.StatusCode == HttpStatusCode.NoContent)
{
recordUri = response.Headers.GetValues("OData-EntityId").FirstOrDefault();
Console.WriteLine("Record URI: {0}", recordUri);
Console.WriteLine("Record created in MS Dynamics.");
}
return recordUri;
}

Hope this helps...!!

Comments or Responses

Login to post response