Power Automate: Email Common Data Service Files related to an Entity

Why?

In my previous post Power Automate: Get Common Data Service Files related to an Entity, I explained on how to enable attachments on a CDS Entity and on how to get those attachments (Notes) related to a CDS Record. But now we want to email those attachments 📧

What?

I know 🙄: we should not want to email attachments but the approach is the same when we want to copy the attachment files to other places like SharePoint or use the attachment files in something like a Modern Approval of Power Automate. This post is using the email example because it is easy to test the results 🤖

How?

First I need to emphasize on how to setup your entity and the attachment functionality as explained in my previous post mentioned above.

1) Once the entities have been setup correctly, we can create a Power Automate Flow that takes into account the possibility that there could be none, one or more Notes related to our Entity. So the Apply to each action will be used and to store all attachments in one place for the rest of the Flow, we will use an Array variable varDocumentsArray so initialize that first:

2) Then we use the Apply to each action to loop through every listed attachment from the Notes entity.

We append an object (every file of the Notes entity attached (related) to our record) to the array with the formula:

{
  "Name": @{items('Apply_to_each_NotesOfInvoice')?['filename']},
  "ContentBytes": @{items('Apply_to_each_NotesOfInvoice')?['documentbody']}
}

The filename property of the file includes the filename extension and the documentbody property is the content of the file. However when using the documentbody property for content from the dynamic content of Power Automate, the file does not open correctly and errors when trying to open:
❌ “We can’t open this file. Something went wrong.” ❌

We apparently need to convert from base64 to Binary and fortunately we can add a conversion in Power Automate using the base64ToBinary function:

{
  "Name": @{items('Apply_to_each_NotesOfInvoice')?['filename']},
  "ContentBytes": @{base64ToBinary(items('Apply_to_each_NotesOfInvoice')?['documentbody'])}
}

3) Finally we can use the varDocumentsArray Array in the Attachments property of the Send an email action:

Be sure to toggle the Attachments property of the action so it is accepted as one array. Once a record has attached Notes, we can send the attached files via an email and open the attachment files as recognized types of previewable documents:

3 thoughts on “Power Automate: Email Common Data Service Files related to an Entity

Leave a comment