Tip #601: Reliably send email in workflow

Sometimes, instead of a simple Send Email action in the workflow, it’s necessary to prepare the email in the workflow (Create Email action), perform some additional manipulations (like adding attachments) and then send it. To do just that, setting email status to Pending Send has been reliably working for everyone since CRM 2011. Until now. Technically, this approach was never documented and the reality of unsupported customizations finally caught up with us.

For one reason or another, setting status to Pending Send no longer works in CRM Online 2015 Update 1 where Dynamics CRM for Outlook is used to send the emails – emails would just sit with Pending Send status and Outlook would duly ignore them while happily sending all other CRM emails. If you find yourself in the same boat, create a custom workflow activity to send draft emails using SendEmailRequest message (code is simplified with any tracing and error handling removed):

public class SendEmail : CodeActivity
{
  [RequiredArgument]
  [Input("Email to send")]
  [ReferenceTarget("email")]
  public InArgument<EntityReference> SourceEmail 
	{ get; set; }

  [Output("Email Subject")]
  public OutArgument<string> Subject { get; set; }
  
  protected override void 
     Execute(CodeActivityContext ec)
  {
    IWorkflowContext context = 
      ec.GetExtension<IWorkflowContext>();

    IOrganizationServiceFactory serviceFactory = 
      ec.GetExtension<IOrganizationServiceFactory>();

    IOrganizationService service = serviceFactory
      .CreateOrganizationService(context.UserId);

    EntityReference email = SourceEmail.Get(ec);
    SendEmailResponse ser = service.Execute(
        new SendEmailRequest()
        {
          EmailId = email.Id,
          IssueSend = true
        }
      ) as SendEmailResponse;

    if (ser != null)
    {
      Subject.Set(ec, ser.Subject);
    }
  }
}

Works like a charm.

Share on FacebookTweet about this on TwitterShare on Google+

One thought on “Tip #601: Reliably send email in workflow

  1. Shawn Stutzman says:

    Thanks for this post! Very helpful.
    For anyone who may find this, and still be using CRM 2011 On premise. This worked for me except that I got an error in my workflow saying “Required field ‘TrackingToken’ is missing.”
    I did some digging around and found that in the SendEmailRequest() function, you can set the TrackingToken.
    I added TrackingToken= “CRM” right after the IssueSend= true and it resolved the issue.

Leave a Reply

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