Skip to main content

Notifications

Microsoft Dynamics CRM (Archived)

Workflow not sending emails

Posted on by Microsoft Employee

First off, let me start by saying I am new to writing workflows and in C#.

I'm currently trying to send emails from a ribbon button. I'm able to add the button and command, and the workflow is triggered. However,

no matter what I do, it won't send an email... Not sure what I'm doing wrong here.

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Xml.Linq;
using System.ServiceModel;
using System.Activities;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Workflow;

namespace SendNotificationsForWeeklyReport
{
    using System;
    using System.Activities;
    using System.ServiceModel;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Workflow;

    public sealed class SendNotificationsForWeeklyReport : CodeActivity
    {
        [Input("Email")]
        [ReferenceTarget("email")]
        public InArgument<EntityReference> Email { get; set; }
        [Input("Account")]
        [ReferenceTarget("account")]
        public InArgument<EntityReference> Account { get; set; }
        protected override void Execute(CodeActivityContext executionContext)
        {
            ITracingService tracingService = executionContext.GetExtension<ITracingService>();
            if (tracingService == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve tracing service.");
            }
            tracingService.Trace("Entered SendNotificationsForWeeklyReport.Execute(), Activity Instance Id: {0}, Workflow Instance Id: {1}",
                executionContext.ActivityInstanceId,
                executionContext.WorkflowInstanceId);
            IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
            if (context == null) throw new InvalidPluginExecutionException("Failed to retrieve workflow context.");


            tracingService.Trace("SendNotificationsForWeeklyReport.Execute(), Correlation Id: {0}, Initiating User: {1}",
                context.CorrelationId,
                context.InitiatingUserId);

            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
            try
            {
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    Entity entity = (Entity)context.InputParameters["Target"];
                    tracingService.Trace("Target Entity is {0} id {1}", entity.LogicalName, entity.Id);
                    Entity email = new Entity("email");
                    //Entity email = service.Retrieve("email", Email.Get(executionContext).Id, new ColumnSet(true));
                    Entity WREntity = service.Retrieve(entity.LogicalName, entity.Id, new ColumnSet(new string[] { "createdby", "am_dwterritory"}));
                    List<Entity> fromList = new List<Entity>();
                    List<Entity> toList = new List<Entity>();
                    if (WREntity.Attributes.Contains("createdby"))
                    {
                        Entity createdby = (Entity) WREntity.Attributes["createdby"];
                        tracingService.Trace("createdby: " + createdby);
                        Entity fromP = new Entity("activityparty");
                        fromP["partyid"] = new EntityReference("systemuser", createdby.Id);
                        fromList.Add(fromP);
                        email.Attributes["from"] = fromList.ToArray();
                        service.Update(email);
                    }

                    QueryExpression teamQuery = new QueryExpression()
                    {
                        EntityName = "weeklyreport_team",
                        ColumnSet = new ColumnSet(true),
                        LinkEntities = 
                        {
                            new LinkEntity
                            {
                                LinkFromEntityName = "weeklyreport",
                                LinkFromAttributeName = "weeklyreportid",
                                LinkToEntityName = "team",
                                LinkToAttributeName = "teamid",
                            }
                        }
                    };

                    teamQuery.Criteria = new FilterExpression();
                    teamQuery.Criteria.AddCondition("weeklyreportid", ConditionOperator.Equal, entity.Id);


                    EntityCollection teams = service.RetrieveMultiple(teamQuery);
                    // getting people in product line team(s)
                    for (int i = 0; i < teams.Entities.Count; i++)
                    {
                        Entity team = teams.Entities[i];
                        tracingService.Trace("Query Expression Retrieved: {0}", team);
                        QueryExpression qe = new QueryExpression();
                        qe.EntityName = "teammembership";
                        qe.ColumnSet = new ColumnSet();
                        qe.ColumnSet.Columns.Add("systemuser");
                        qe.LinkEntities.Add(new LinkEntity("team", "systemuser", "teamid", "accountid", JoinOperator.Inner));
                        qe.Criteria = new FilterExpression();
                        qe.Criteria.AddCondition("teamid", ConditionOperator.Equal, team.Id);

                        EntityCollection ec = service.RetrieveMultiple(qe);
                        foreach (Entity user in ec.Entities)
                        {
                            if (user.Attributes.Contains("internalemailaddress"))
                            {
                                tracingService.Trace("Get Email " + user.Attributes["internalemailaddress"].ToString());
                                Entity toParty = new Entity("activityparty");
                                toParty["partyid"] = new EntityReference("systemuser", user.Id);
                                toList.Add(toParty);
                            }
                        }
                    }

                    // retrieving additional recipients
                    QueryExpression userQuery = new QueryExpression()
                    {
                        EntityName = "issi_issi_weeklyreport_systemuser",
                        ColumnSet = new ColumnSet(true),
                        LinkEntities = 
                        {
                            new LinkEntity
                            {
                                LinkFromEntityName = "weeklyreport",
                                LinkFromAttributeName = "weeklyreportid",
                                LinkToEntityName = "systemuser",
                                LinkToAttributeName = "systemuserid",
                            }
                        }
                    };
                    userQuery.Criteria = new FilterExpression();
                    userQuery.Criteria.AddCondition("weeklyreportid", ConditionOperator.Equal, entity.Id);

                    EntityCollection users = service.RetrieveMultiple(userQuery);
                    foreach (Entity user in users.Entities)
                    {
                        Entity toParty = new Entity("activityparty");
                        toParty["partyid"] = new EntityReference("systemuser", user.Id);
                        toList.Add(toParty);
                    }

                    email.Attributes["to"] = toList.ToArray();
                    service.Update(email);
                    Guid emailid = service.Create(email);
                    tracingService.Trace("Sending Mail");
                    SendEmailRequest SendEmail = new SendEmailRequest();
                    SendEmail.EmailId = emailid;
                    SendEmail.TrackingToken = "";
                    SendEmail.IssueSend = true;
                    tracingService.Trace("Sending Mail");
                    SendEmailResponse res = (SendEmailResponse)service.Execute(SendEmail);
                }
            }
            catch (FaultException<OrganizationServiceFault> e)
            {
                tracingService.Trace("Exception: {0}", e.ToString());

                // Handle the exception.
                throw;
            }

            tracingService.Trace("Exiting SendNotificationsForWeeklyReport.Execute(), Correlation Id: {0}", context.CorrelationId);
        }
    }
}

*This post is locked for comments

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Workflow not sending emails

    so should I create the email right after I create the email entity up top?

    I'm not sure whether I should use a template that I defined in the GUI or create a new one. Thats why I have commented out 

    Entity email = service.Retrieve("email", Email.Get(executionContext).Id, new ColumnSet(true));

    I could just create a new email by doing this...

    Entity email = new Entity("email");
    Guid emailid = service.Create(email);

    Not really sure which way I should use. There are attachments in this email as well.

  • Aric Levin Profile Picture
    Aric Levin 30,188 on at
    RE: Workflow not sending emails

    Why are you creating an email after you are updating it?

    Aren't you passing the Email Id parameter to your Custom Workflow Activity?

  • RaviKashyap Profile Picture
    RaviKashyap 55,410 on at
    RE: Workflow not sending emails

    So the email status which was created by this workflow is Draft? Can you try sending that email from CRM UI.

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Workflow not sending emails

    I know the email configuration to send emails is correct in our CRM system, because the system sends emails in other workflows...

    I registered the email template to be sent in the workflow definition under processes...

    Its status shows "Draft" in advanced find.

  • Suggested answer
    RaviKashyap Profile Picture
    RaviKashyap 55,410 on at
    RE: Workflow not sending emails

    Hi,

    Looking at your send email code, nothing seems to be wrong there. Could you please check if you have configured the email configuration to send emails from crm?

    Try sending an email from crm manually by creating an email activity and sending. If that doesn't work then you need to configure/ fix the email configuration.

    Also, as you have the code to create the email, that email must exist in your crm. Try to find that email and see the status. Is it pending send? If yes then definitely the issue is with your email configuration.

    Hope this helps.

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Community AMA December 12th

Join us as we continue to demystify the Dynamics 365 Contact Center

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,240 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,104 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans