Send a Dynamics 365 Email using C#

5 Comments

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:

 

THANKS FOR READING. BEFORE YOU LEAVE, I NEED YOUR HELP.
 

I AM SPENDING MORE TIME THESE DAYS CREATING YOUTUBE VIDEOS TO HELP PEOPLE LEARN THE MICROSOFT POWER PLATFORM.

IF YOU WOULD LIKE TO SEE HOW I BUILD APPS, OR FIND SOMETHING USEFUL READING MY BLOG, I WOULD REALLY APPRECIATE YOU SUBSCRIBING TO MY YOUTUBE CHANNEL.

THANK YOU, AND LET'S KEEP LEARNING TOGETHER.

CARL

https://www.youtube.com/carldesouza

 

ABOUT CARL DE SOUZA

Carl de Souza is a developer and architect focusing on Microsoft Dynamics 365, Power BI, Azure, and AI.

carldesouza.comLinkedIn Twitter | YouTube

 

5 Responses to Send a Dynamics 365 Email using C#

  1. Hi Carl,
    Very informative article.
    I am trying to achieve The same with power shell using crm sdk.
    I am not able to assign the frompartyactivity to the $email[“to”]

    Can you help me in converting this line to power shell
    email[“to”] = new Entity[] { toActivityParty };
    Highly appreciate your help.
    Thanks

  2. This is fantastic and i can get one items added to the “to” field, but how do i go about adding multiple recipients?

    • @Rameez Maybe a little late, but to answer youre question just add more activitypartys to the entitycollection like this:

      var to = new EntityCollection();
      var person1 = new Entity(“activityparty”); person1[“partyid”] = new entityreference(“contact”, contact1Id);
      var person2 = new Entity(“activityparty”); person2[“partyid”] = new entityreference(“contact”, contact2Id);
      var person3 = new Entity(“activityparty”); person3[“partyid”] = new entityreference(“contact”, contact3Id);

      to.Entities.Add(person1);
      to.Entities.Add(person2);
      to.Entities.Add(person3);

      email[“to”] = to;

  3. Hi Carl de Souza,

    This is really nice. Can I set anyother user in “From” rather the user who is executing this plugin? I want to set “From” dynamically based on few conditions.

Leave a Reply

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