Send a Dynamics 365 Email using C#

Leave a comment

We will go through an example of sending an email in Dynamics 365 using C#.

We have a contact in Dynamics 365 called Bob Smith. We will send the email to him.

First, create a new console app:

Using NuGet, add references and then the using statements:

using Microsoft.Xrm.Tooling.Connector;
using Microsoft.Xrm.Sdk;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;

Now add the code.

We will first get the current user using WhoAmIResponse.  Then, we will create a query expression to loop through all contacts whose name is Bob Smith. We will create an activity party for the from email (i.e. the current user) and the to email (i.e. Bob Smith).

After creating the email, we will send it using SendEmailRequest:

                var connectionString = @"AuthType = Office365; Url = https://yourtenant.crm.dynamics.com/;Username=youremail;Password=yourpassword";
                CrmServiceClient conn = new CrmServiceClient(connectionString);

                IOrganizationService service;
                service = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;

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

                // We will get the contact id for Bob Smith using Retrieve
                ConditionExpression conditionExpression = new ConditionExpression();
                conditionExpression.AttributeName = "fullname";
                conditionExpression.Operator = ConditionOperator.Equal;
                conditionExpression.Values.Add("Bob Smith");

                FilterExpression filterExpression = new FilterExpression();
                filterExpression.Conditions.Add(conditionExpression);

                QueryExpression query = new QueryExpression("contact");
                query.ColumnSet.AddColumns("contactid");
                query.Criteria.AddFilter(filterExpression);

                EntityCollection entityCollection = service.RetrieveMultiple(query);
                foreach (var a in entityCollection.Entities)
                {
                    // We will send the email from this current user
                    Entity fromActivityParty = new Entity("activityparty");
                    Entity toActivityParty = new Entity("activityparty");

                    Guid contactId = (Guid)a.Attributes["contactid"];

                    fromActivityParty["partyid"] = new EntityReference("systemuser", userId);
                    toActivityParty["partyid"] = new EntityReference("contact", contactId);

                    Entity email = new Entity("email");
                    email["from"] = new Entity[] { fromActivityParty };
                    email["to"] = new Entity[] { toActivityParty };
                    email["regardingobjectid"] = new EntityReference("contact", contactId);
                    email["subject"] = "This is the subject";
                    email["description"] = "This is the description.";
                    email["directioncode"] = true;
                    Guid emailId = service.Create(email);

                    // Use the SendEmail message to send an e-mail message.
                    SendEmailRequest sendEmailRequest = new SendEmailRequest
                    {
                        EmailId = emailId,
                        TrackingToken = "",
                        IssueSend = true
                    };

                    SendEmailResponse sendEmailresp = (SendEmailResponse)service.Execute(sendEmailRequest);
                    Console.WriteLine("Email sent");
                    Console.ReadLine();
                }

If we run this without sending the email, we can see the result below, with the email activity created status = Draft. In running with the send email, we can see the status is sent:

 

Leave a Reply

Your email address will not be published. Required fields are marked *

three × 5 =