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
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.
Why are you creating an email after you are updating it?
Aren't you passing the Email Id parameter to your Custom Workflow Activity?
So the email status which was created by this workflow is Draft? Can you try sending that email from CRM UI.
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.
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.
Stay up to date on forum activity by subscribing. You can also customize your in-app and email Notification settings across all subscriptions.
André Arnaud de Cal... 291,240 Super User 2024 Season 2
Martin Dráb 230,104 Most Valuable Professional
nmaenpaa 101,156