Power Automate: Send an email using the Email Template – Part 1

By | September 23, 2020

Introduction

What options do we have for sending an email using the email template on specific events/actions in Dynamics CRM?

We have a classic workflow with ‘Send Email’ and ‘Use Template’ action or a Plugin with ‘InstantiateTemplate’ and ‘SendEmail’ request for this. Now we can do the same thing using Power Automate as well.

This blog will illustrate how we can create a Power Automate Flow to send an email using the Email Template.

Let us consider a scenario: a company has an inquiry form on their website. On each submission, a new lead gets created in the CRM and for each newly created lead, an email with a thank you message should be sent to the customer.

Setup trigger for Power Automate

We will create a Power Automate Flow that will get triggered on the creation of the Leads record. For this, we will select ‘When a record is created, updated or deleted’ trigger and will select ‘Create’ as the trigger condition. If you want to learn more about scope, refer to this blog to know how to use Scope with Common Data Service in Microsoft Flow.

Retrieve Email template

We will add ‘List Records’ step to retrieve the Email Template by its name (Title). We are retrieving the below template.

Add a filter query to retrieve template by the title as shown below

Send an email using the Email Template in Power Automate

This step will return the ‘Lead Reply-Web Site Visit’ template. We will use the GUID of this template in the next step.

Use ‘SendEmailFromTemplate’ action

This action is used to send an email using the Email Template. To execute this in Power Automate we need to add ‘Perform an unbound action’ step.

For this step/action, we need to pass the below parameters,

Action Name: Select SendEmailFromTemplate’ from the list of actions.

TemplateId: GUID of the Email Template. In the second step, we retrieved the email template, we can use following expression to get the GUID of the template.

first(body(‘List_records’)?[‘value’])?[‘templateid’]

Regarding: This is the Record to be set as the regarding of the email. Here we will pass the newly created Lead as the regarding. Pass the record as the following

/leads(triggerOutputs()?[body/leadid])

Target: This is the parameter where we need to pass the sender and recipients of the email in JSON format. Below is the JSON structure

{

“email_activity_parties”: [
{
“partyid_<entitylogicalname>@odata.bind”: “/<entitysetname>(<guid of the record>)”,
“participationtypemask”: 1
},
{
“partyid_<entitylogicalname>@odata.bind”: “/<entitysetname>(<guid of the record>)”,
“participationtypemask”: 2
}
],
“@@odata.type”: “Microsoft.Dynamics.CRM.email”

}

It is important to understand the Target parameter’s JSON structure because this is the place where we set TO, CC, BCC and FROM for the email.

In the above JSON, I have used ‘participationtypemask’ as 1 and 2. Use 1 to set FROM and use 2 to set ‘To’.

If you want to set CC and BCC then use 3 and 4 as ‘participationtypemask’ respectively.

Send an email using the Email Template in Power Automate 1

This way ‘SendEmailFromTemplate’ action will allow you to send an email using the Email Template. Subject and email body will come from the email template and Sender, Recipients (To, CC, BCC) will be set based on the Target Parameter.

Below is my “Perform an unbound action” and its JSON

Send an email using the Email Template in Power Automate

TemplateId is the GUID of the template retrieved from the second ‘List Records’ step, ‘Regarding’ is the entity object of the lead that is being created and in the Target parameter, ‘FROM’ is being set to Owner of the lead and ‘To’ is set to the lead entity object.

{
“email_activity_parties”: [
{
“partyid_systemuser@odata.bind”: “/systemusers(@{triggerOutputs()?[‘body/_ownerid_value’]})”,
“participationtypemask”: 1
},
{
“partyid_lead@odata.bind”: “/leads(@{triggerOutputs()?[‘body/leadid’]})”,
“participationtypemask”: 2
},

{
“partyid_systemuser@odata.bind”: “/systemusers(c308eef1-1de7-ea11-a817-000d3a0a82a5)”,
“participationtypemask”: 3
},
{
“addressused”: “sam@test.com”,
“participationtypemask”: 4
},

{
“addressused”: “john@test.com”,
“participationtypemask”: 4
}

],
“@@odata.type”: “Microsoft.Dynamics.CRM.email”
}

Sometimes, you may want to send an email to the email address which doesn’t exist in your system. In that case, we can use the ‘addressused’ parameter. In the above code snippet, you can see I have set sam@test.com for BCC.

In addition, you may want to send more than one recipient in either TO, CC or in BCC. It is possible to set multiple objects in TO, CC and in BCC. You just need to add multiple entries in the ‘email_activity_parties’.

Below is how my final working Power Automate Flow looks like

Send an email using the Email Template in Power Automate

Below is the screenshot of the newly generated mail using the Email Template

Send an email using the Email Template in Power Automate

Note: If any of your recipients is either a contact, lead or account and is marked as do not allow for Email then the flow will fail with an error saying, “Recipient of type ‘Lead’ with ID ‘xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx’ is marked as non-Emailable”

Send an email using the Email Template in Power Automate

Conclusion

We can now consider Power Automate Flow to send automated email using the Email Template using “SendEmailFromTemplate” action. In the Part 2 blog, we will see how to send bulk email messages using Power Automate.

Reference: https://docs.microsoft.com/en-us/dynamics365/customer-engagement/web-api/sendemailfromtemplate?view=dynamics-ce-odata-9

One Pic = 1000 words! Analyze data 90% faster with visualization apps!

Get optimum visualization of Dynamics 365 CRM data with –
Kanban Board – Visualize Dynamics 365 CRM data in Kanban view by categorizing entity records in lanes and rows as per their status, priority, etc.
Map My Relationships – Map My Relationships – Visualize connections and relationships between Dynamics 365 CRM entities or related records in a Mind Map view.

13 thoughts on “Power Automate: Send an email using the Email Template – Part 1

  1. BeckFish

    Hi Roohi, we want our email to be Set Regarding an entity different from the recipient of the email. The email template is for a Contact, but we want to set regarding a related custom entity created earlier in the Flow. The Flow fails with the message ‘Template type is incorrect for given objectType 10224 != 2 template.templatetypecode’ (10224 being the objecttypecode for our custom entity, confirmed by webAPI; 2 is Contact).

    Have you come across this? And can you think of any way around it? Incidentally the unbound action SendTemplate (bulk email) equivalent to this does allow you to Set Regarding this custom entity while still sending To the Contact – tried and tested.

    Thank you!

    Reply
    1. Inogic

      Hi,

      Yes, the Flow will throw an error if your Email template is for contact and trying to set regarding as a different entity. You can use unbound SendTemplate action but it will send emails only if the “Bulk Email” is set to allow on the contact record. If this is not going to work in your case then you would need to programmatically send the email. You would need to retrieve the template created in CRM and create and send an Email entity record by replacing the placeholder added in the Email template with the data from the recipient/Contact. Also, you need to set the regarding as the custom entity record.

      Hope this helps!
      Thanks

      Reply
  2. BeckFish

    Thank you for your quick and helpful response! I tried (and failed…) in what seemed to be an alternative workaround of getting the sent email message in a subsequent step and updating the Regarding from there, however the value of ‘message correlated activityid’ (as offered by add Dynamic Content) turns out to not be a guid, and when I tried by writing my own expression to wire the Get Record to the activityid (as correctly identified in the output of the unbound action step) it errored too, saying it couldn’t find the recordid.
    Does this sound right to you that this is a dead end – you can’t subsequently ‘get’ the email created by ‘sendEmailFromTemplate’? Hope that makes sense.

    Reply
    1. Inogic

      You cannot update the sent email message. You must update the email before it is getting sent. You can try first by executing InstantiateTemplateRequest. Pass your global template ID to this request. This request will return a response that will contain the Subject, email body, etc. After this request, create an email record and set Regarding and replace the placeholders from the email body.

      Hope this provides some clarity.

      Reply
      1. BeckFish

        Ahh that didn’t work for me – in the InstantiateTemplate along with the template I put ObjectType as contact and ObjectID as dynamic Contact guid, not sure where an array would come into it. (I tried both with original templatewhich was a Contact template, and also a test global one in case that mattered).
        ResponseSwaggerSchemaValidationFailure. The API ‘commondataserviceforapps’ returned an invalid response for workflow operation ‘Perform_an_unbound_action_InstantiateTemplate’ of type ‘OpenApiConnection’. Error details: ‘The API operation ‘PerformUnboundAction’ requires the property ‘body’ to be of type ‘Array’ but is of type ‘Object’.’

        Thanks for your help. It is annoying as we wanted to use Flow (over workflow) but they want easy access from UI to edit the D365 template themselves, and we need it to send independent of the allowbulkemail field on Contact.

        Reply
    1. Inogic

      Hi Nilesh,

      To send email to multiple recipients, you need to add multiple email activity parties of ‘participationtypemask’ as 2 in the Target,
      {
      “email_activity_parties”: [
      {
      “partyid_@odata.bind”: “/()”,
      “participationtypemask”: 1
      },
      {
      “partyid_@odata.bind”: “/()”,
      “participationtypemask”: 2
      },

      {
      “partyid_@odata.bind”: “/()”,
      “participationtypemask”: 2
      },

      {
      “partyid_@odata.bind”: “/()”,
      “participationtypemask”: 2
      }
      ],
      “@@odata.type”: “Microsoft.Dynamics.CRM.email”

      }

      Here participationtypemask 2 is the To recipient.

      Hope this helps,
      Thanks!

      Reply
  3. Christopher Cambridge

    Great post!! Thank you. I am hoping you can provide a little help with an error I’m getting in the final perform an unbound action step of SendEmailFromTemplate.

    My data: (a string, complied earlier in the flow)
    TemplateID: 8c182596-c481-eb11-a812-001dd80496bc
    Regarding: xxx_myentitynames(c327dx32-aa85-eb11-8ced-00155da14786
    Target:
    {“email_activity_parties”: [
    {“partyid_systemuser@odata.bind”: “/systemusers(9a268c41-d936-eb11-a813-001dd8309f30)”,”participationtypemask”: 1},
    {“partyid_systemusers@odata.bind”: “/systemusers(bb763206-5cf4-ea11-a816-001dd83098a0)”,”participationtypemask”: 2},
    {“partyid_systemusers@odata.bind”: “/systemusers(425884a6-56f4-ea11-a816-001dd83098a0)”,”participationtypemask”: 2},
    {“partyid_systemusers@odata.bind”: “/systemusers(bb763206-5cf4-ea11-a816-001dd83098a0)”,”participationtypemask”: 2},
    {“partyid_systemusers@odata.bind”: “/systemusers(c4761aba-58f4-ea11-a816-001dd83098a0)”,”participationtypemask”: 2}],
    “@@odata.type”: “Microsoft.Dynamics.CRM.email”}

    The Error:
    An error occurred while validating input parameters: Microsoft.OData.ODataException: Bad Request – Error in query syntax.\r\n at Microsoft.OData.UriParser.ODataPathParser.ExtractSegmentIdentifierAndParenthesisExpression(String segmentText, String& identifier, String& parenthesisExpression)\r\n at Microsoft.OData.UriParser.ODataPathParser.CreateFirstSegment(String segmentText)\r\n at Microsoft.OData.UriParser.ODataPathParser.ParsePath(ICollection`1 segments)\r\n at Microsoft.OData.UriParser.ODataPathFactory.BindPath(ICollection`1 segments, ODataUriParserConfiguration configuration)\r\n at Microsoft.OData.UriParser.ODataUriParser.Initialize()\r\n at Microsoft.Crm.Extensibility.OData.CrmEdmEntityReference.CreateCrmEdmEntityReference(Uri link, IEdmModel edmModel, CrmODataExecutionContext context, EntitySetSegment& entitySetSegment)\r\n at Microsoft.Crm.Extensibility.ODataV4.ODataParameterReaderExtensions.TryReadFlowPrimitiveData(ODataParameterReader oDataParameterReader, ODataDeserializerContext readContext, CrmEdmEntityObject& result)\r\n at Microsoft.Crm.Extensibility.ODataV4.ODataParameterReaderExtensions.TryReadFlowPrimitive(ODataParameterReader oDataParameterReader, ODataDeserializerContext readContext, CrmEdmEntityObject& result)\r\n at Microsoft.Crm.Extensibility.ODataV4.CrmODataActionPayloadDeserializer.Read(ODataMessageReader messageReader, Type type, ODataDeserializerContext readContext)\r\n at System.Web.OData.Formatter.ODataMediaTypeFormatter.ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)

    Reply
    1. Inogic

      Hi Christopher,

      The syntax seems correct. But I see the problem with the double quotes used in the expression. Copy your data in notepad and replace all the double quotes again.

      Hope that helps!
      Thanks.

      Reply
  4. David Garcia Martinez

    Hello! Your post was so helpful for me! However, I want to include a feature that doesn’t seem to be here. I want to make the email templates that I sent from Power Automate with this unbound action Non Visible in the Portal. Make this from CRM Process is as simple as disabling it by a radio control, but from Power Automate seems to be more complicated, maybe introducing a new JSON variable? I will really appreciate help for this question.

    Thanks in advance!

    Reply
    1. Inogic

      Which portal you are referring to? The Power Apps Portal?
      I am not if I have understood your requirement correctly. But you cannot show hide something from Power Automate. Please elaborate your scenario more in detail.

      Thanks!

      Reply
  5. Tejaswini

    Hi Inogic,

    what if we have to dynamically send multiple users like array of users in either to or cc recipients

    Reply
    1. Inogic

      Yes, you can add multiple users in To or in CC recipients. You need add those many parties with their participationtypemask(2=To, 3=CC) in the email_activity_parties array. See below example where 2 users have been added in To and 3 users added in CC.

      {
      “email_activity_parties”: [
      {
      “partyid_systemuser@odata.bind”: “/systemusers(@{triggerOutputs()?[‘body/_ownerid_value’]})”,
      “participationtypemask”: 1
      },
      {
      “partyid_lead@odata.bind”: “/leads(@{triggerOutputs()?[‘body/leadid’]})”,
      “participationtypemask”: 2
      },
      {
      “partyid_systemuser@odata.bind”: “/systemusers(c308eef1-1de7-ea11-a817-000d3a0a82a6)”,
      “participationtypemask”: 2
      },
      {
      “partyid_systemuser@odata.bind”: “/systemusers(c308eef1-1de7-ea11-a817-000d3a0a82a7)”,
      “participationtypemask”: 3
      },
      {
      “partyid_systemuser@odata.bind”: “/systemusers(c308eef1-1de7-ea11-a817-000d3a0a82a8)”,
      “participationtypemask”: 3
      },
      {
      “partyid_systemuser@odata.bind”: “/systemusers(c308eef1-1de7-ea11-a817-000d3a0a82a9)”,
      “participationtypemask”: 3
      },
      ],
      “@@odata.type”: “Microsoft.Dynamics.CRM.email”
      }

      Hope this helps!

      Thanks!

      Reply

Leave a Reply

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