Wicked Smart Data
LearnInsightsAboutContact
Sign InLet's Build
LearnInsightsAboutContact
Sign InLet's Build
Wicked Smart Data

Intelligence, automation, and expert execution — plus an elite library of free knowledge. We turn complexity into competitive advantage.

Start a conversation

Platform

  • Learning Paths
  • Insights
  • RSS Feed

Company

  • About
  • Contact
  • Work With Us

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Wicked Smart Data. All rights reserved.

Intelligence · Automation · Advantage

All Insights
Power Automate

Automating Multi-File Email Attachment Processing with Power Automate: Filtering by Type, Saving to SharePoint Folders, and Triggering Approval Flows Based on Document Content

Learn how to build a production-ready Power Automate flow that processes every attachment from an incoming email, routes files to type-specific SharePoint folders, and triggers content-aware approval workflows — automatically, every time. This deep-dive lesson covers extension parsing, collision-safe naming, dynamic folder paths, and layered approval routing logic.

🔥 Expert27 min readNov 28, 2026Updated Nov 28, 2026
Automating Multi-File Email Attachment Processing with Power Automate: Filtering by Type, Saving to SharePoint Folders, and Triggering Approval Flows Based on Document Content
On this page
  • Introduction
  • Prerequisites
  • Understanding the Architecture Before You Build
  • Setting Up the Trigger: Capturing Emails with Attachments
  • Initializing Variables for State Management
  • Building the Attachment Loop and File Type Classification
  • Extracting the File Extension
  • Building the Classification Condition
  • Generating Collision-Safe Filenames
  • Saving Files to SharePoint with Dynamic Folder Paths
  • Handling Subfolder Creation
  • Capturing the SharePoint File ID for Later Use
  • Content-Based Approval Routing: Going Beyond File Type
  • Triggering the Approval Flow
  • Handling the Approval Response
  • Updating the Processed Files Log
  • Handling the "No Attachments" Edge Case
  • Hands-On Exercise
  • Common Mistakes and Troubleshooting
  • "My loop only processes the first attachment"
  • "SharePoint Create file fails with 'The specified folder does not exist'"
  • "The approval action times out or the flow just stops"
  • "The file content is corrupted in SharePoint"
  • "The extension parser returns the full filename for files without extensions"
  • "My approval fires for every PDF, not just contracts"
  • Extending the Flow: Advanced Patterns Worth Knowing
  • Using AI Builder for Richer Content Classification
  • Chaining Downstream Systems
  • Applying Managed Metadata Tags
  • Summary and Next Steps

Automating Multi-File Email Attachment Processing with Power Automate: Filtering by Type, Saving to SharePoint Folders, and Triggering Approval Flows Based on Document Content

Introduction

Picture this: your finance team receives a daily vendor email that contains five attachments — an invoice PDF, a remittance Excel spreadsheet, a scanned W-9 form, a draft contract in Word, and a logo PNG the vendor inexplicably includes in every email. Your current process? Someone opens the email, manually downloads each file, decides where it goes, drags it to the right SharePoint folder, and — if it's a contract — forwards it to legal for review. That's eight manual steps, repeated dozens of times a week, by someone who has better things to do.

The problem isn't just the tedium. It's the inconsistency. Files land in the wrong folders. Contracts sit in inboxes waiting for someone to remember to route them. The PDF that needed VP approval before processing gets paid without it. When you automate this properly with Power Automate, you don't just eliminate the manual work — you enforce the rules every single time, without anyone having to remember them.

By the end of this lesson, you'll have built a production-worthy flow that intercepts incoming emails with attachments, iterates through every file, routes each one to a type-appropriate SharePoint folder, and conditionally kicks off an approval workflow when the document content meets specific criteria. You'll understand the architectural decisions behind each design choice, the edge cases that will bite you if you ignore them, and the expression patterns that make it all work reliably.

What you'll learn:

  • How to trigger a flow on incoming emails and extract every attachment, regardless of how many are present
  • How to filter attachments by file type using extension parsing and content-type inspection
  • How to dynamically construct SharePoint folder paths and save files with collision-safe naming
  • How to inspect document metadata and content signals to conditionally trigger approval flows
  • How to chain SharePoint file saving, metadata updates, and approval initiation into a coherent, error-resilient pipeline

Prerequisites

Before diving in, you should be comfortable with the Power Automate designer interface and have built at least a few flows that use conditions and loops. If you need a refresher on how conditions and Apply to Each work together, Working with Conditions, Loops, and Variables in Power Automate will get you current. You'll also want a SharePoint site with a document library already created — we'll build the folder structure as part of this lesson, but we won't cover library provisioning from scratch. A working Outlook (Office 365) connection and an approvals-capable license (Microsoft 365 Business Standard or above) round out the technical requirements.


Understanding the Architecture Before You Build

The temptation with complex flows is to jump straight into the designer and start dragging actions. Resist it. This flow has four distinct phases that need to be designed separately before they're stitched together:

Phase 1 — Trigger and email intake: Capturing the email, understanding what's in it, and preparing to iterate.

Phase 2 — Attachment iteration and type classification: Looping through every attachment and categorizing each one by file type.

Phase 3 — Folder routing and file saving: Dynamically determining the destination path and writing the file to SharePoint with appropriate metadata.

Phase 4 — Content-based approval triggering: Inspecting enough about the document to decide whether a human needs to review it, then initiating the right approval pattern.

Each phase has its own failure modes and design trade-offs. We'll cover them as we go. What matters architecturally is that these phases are sequential and stateful — the output of Phase 2 (the file type classification) directly controls Phase 3 (where the file goes), and both Phase 2 and Phase 3 inform Phase 4 (whether approval fires). That dependency chain shapes how we store intermediate values.

Key insight

In Power Automate, variables initialized before a loop are readable and writable inside that loop. Compose actions inside a loop produce values only accessible within that loop iteration. Design your state management around this constraint from the start, or you'll find yourself rewriting the flow after the fact.


Setting Up the Trigger: Capturing Emails with Attachments

Navigate to Power Automate, create a new Automated cloud flow, and search for the trigger "When a new email arrives (V3)" from the Office 365 Outlook connector. This is the V3 trigger — use it, not the older versions. The V3 trigger gives you richer filtering options and better handling of attachments.

Once the trigger is on the canvas, expand its advanced options. You'll configure several fields:

Folder: Set this to the specific Inbox folder or subfolder where vendor emails arrive. If your team uses Outlook rules to pre-sort emails into a "Vendor Invoices" folder, point the trigger there. This prevents the flow from firing on every single incoming email and keeps your trigger efficient. For learning how triggers evaluate conditions, Power Automate Triggers: When to Start a Flow covers the internals in detail.

Include Attachments: Set this to Yes. This is non-negotiable — without it, the trigger payload won't include attachment content, and you'll have nothing to process.

Only with Attachments: Set this to Yes. This prevents the flow from running on emails that happen to match your other criteria but contain no files.

Subject Filter: Depending on your scenario, you might filter on a subject keyword like "Invoice" or "Vendor Submission." Be careful with this — if the filter is too narrow, you'll miss valid emails; if it's too broad, you'll process things you shouldn't.

The trigger payload, when it fires, will include an Attachments array. Each element of that array contains:

  • Name — the filename including extension
  • ContentBytes — the base64-encoded file content
  • ContentType — the MIME type declared by the email client

Understanding these three fields is essential. Name is what you'll parse to determine file type. ContentBytes is what you'll write to SharePoint. ContentType is a secondary signal for classification that you should never trust exclusively — senders can misconfigure MIME types, and some email clients just declare everything as application/octet-stream.

Warning

The When a new email arrives (V3) trigger has a polling interval — it doesn't respond to emails in true real-time. By default, it checks every few minutes. For time-critical processing, you can reduce this interval in the trigger settings, but be aware that more frequent polling consumes more API calls against your connector limits.


Initializing Variables for State Management

Before the loop, you need to initialize the variables that will carry state through each iteration and potentially across the entire flow run. Add the following "Initialize variable" actions after the trigger, in this order:

varCurrentFileExtension — Type: String, Value: (empty) This will hold the parsed extension of the file currently being processed.

varDestinationFolder — Type: String, Value: (empty) This will hold the resolved SharePoint subfolder path for the current attachment.

varApprovalRequired — Type: Boolean, Value: false This will flag whether the current file needs to go through an approval process.

varSafeFileName — Type: String, Value: (empty) This will hold the collision-safe version of the filename (more on this shortly).

varProcessedFiles — Type: Array, Value: [] This accumulates a log of every file processed during the run, which you can use at the end to send a summary email or update a SharePoint tracking list.

You might wonder why we're using variables rather than Compose actions for some of these. The answer is scope. Compose actions exist within a single action's output — you can reference a Compose from earlier in the flow, but you can't update it. Variables can be Set inside loops, which is exactly what we need as we process one attachment after another.


Building the Attachment Loop and File Type Classification

Add an "Apply to each" action. For the input, select the Attachments from the trigger's dynamic content. Everything that follows in this section goes inside this loop.

Extracting the File Extension

The first thing you need to know about each attachment is its type. Add a "Set variable" action targeting varCurrentFileExtension. The value expression needs to extract everything after the last period in the filename:

toLower(last(split(triggerOutputs()?['body/attachments/0/name'], '.')))

Wait — that hardcoded index 0 is wrong for a loop. Inside an Apply to Each, you use the current item reference instead. The correct expression referencing the loop's current item:

toLower(last(split(items('Apply_to_each')?['name'], '.')))

What this does: items('Apply_to_each')?['name'] pulls the filename from the current loop iteration. split(..., '.') breaks it into an array on the period character. last(...) takes the final element, which is the extension. toLower(...) normalizes it so .PDF and .pdf match the same condition.

Warning

This expression fails silently on files with no extension — last(split('README', '.')) returns README, which won't match any of your extension conditions and will route the file to whatever your default/fallback path is. That's actually fine behavior, but you should be aware of it and ensure your fallback path exists.

For filenames with multiple dots like invoice.final.v2.pdf, this correctly extracts pdf because last() takes the final split segment.

Building the Classification Condition

Now add a "Condition" action (or a "Switch" action for cleaner multi-branch logic — Switch is the right choice here). Set the Switch input to varCurrentFileExtension.

Your cases should cover:

Case: pdf These are likely invoices, contracts, or scanned documents. Set varDestinationFolder to /Documents/Vendor Files/PDFs and evaluate further for approval routing.

Case: xlsx, xls (you'll need separate cases or handle this with OR logic in a Condition) These are likely remittance advices or data exports. Set varDestinationFolder to /Documents/Vendor Files/Spreadsheets.

Case: docx, doc Word documents — could be contracts, could be letters. Set varDestinationFolder to /Documents/Vendor Files/Word Documents.

Case: png, jpg, jpeg, gif Images. Set varDestinationFolder to /Documents/Vendor Files/Images.

Default: Everything else. Set varDestinationFolder to /Documents/Vendor Files/Unsorted.

Tip

If you find yourself with many file type cases, consider maintaining a SharePoint list that maps extensions to folder paths, then do a "Get items" at the start of the flow to load that mapping into a variable. This externalizes the routing configuration so non-developers can update it without touching the flow. It's more complex initially but dramatically easier to maintain as your requirements evolve.

Inside each case, also set varApprovalRequired appropriately. For the PDF and DOCX cases, you'll set this to true for now — we'll refine this logic significantly in the content-based approval section.

Understanding how to work cleanly with branching logic like this is covered in depth in Working with Conditions, Loops, and Variables in Power Automate, including how Switch actions compare to nested conditions for readability and performance.


Generating Collision-Safe Filenames

Here's a scenario that will break a naive implementation: two emails arrive within minutes of each other, both containing a file named invoice.pdf. The second file silently overwrites the first in SharePoint. You may never notice until someone asks why their document is gone.

The solution is to generate a unique filename before saving. Add a "Set variable" action for varSafeFileName using this expression pattern:

concat(
  replace(items('Apply_to_each')?['name'], 
    concat('.', toLower(last(split(items('Apply_to_each')?['name'], '.')))), 
    ''
  ),
  '_',
  formatDateTime(utcNow(), 'yyyyMMddHHmmss'),
  '_',
  substring(guid(), 0, 8),
  '.',
  varCurrentFileExtension
)

Breaking this down: we take the original filename, strip its extension, append a timestamp formatted as 20240315143022, append an 8-character slice of a GUID for additional uniqueness, then reattach the extension. A file named invoice.pdf becomes invoice_20240315143022_a3f8c1d9.pdf.

This approach is deliberate. You could just use a GUID as the entire filename, but then you lose human readability — someone browsing the SharePoint folder should be able to tell at a glance what the file is. Preserving the original name as a prefix keeps that context while the timestamp makes ordering intuitive and the GUID suffix guarantees uniqueness.

For more expression techniques like this string manipulation pattern, Mastering Dynamic Expressions and the Power Automate Formula Language: String, Date, and Array Functions for Real-World Data Manipulation is the definitive reference.


Saving Files to SharePoint with Dynamic Folder Paths

Now we're ready to write the file. Add a "Create file" action from the SharePoint connector. Configure it:

Site Address: Your SharePoint site URL.

Folder Path: Use varDestinationFolder. This is the value we set in the Switch action, so it will be the correct subfolder for whatever file type we're processing.

File Name: Use varSafeFileName.

File Content: items('Apply_to_each')?['contentBytes']

The contentBytes field is already base64-encoded binary data, which is exactly what SharePoint's "Create file" action expects. You don't need to decode it — the connector handles that translation internally.

Handling Subfolder Creation

If the destination subfolder doesn't exist yet, the "Create file" action will fail with an error rather than creating the folder. You have two options:

Option A — Pre-create the folders: Before the loop, run a one-time setup that ensures all expected subfolders exist using the "Create new folder" action from the SharePoint connector. This is the simplest approach if your folder structure is static.

Option B — Defensive folder creation inside the loop: Before each "Create file" action, attempt to create the folder and configure that action to "Continue on error" (using the "Configure run after" settings on subsequent actions). If the folder already exists, the creation action fails silently, the file save proceeds, and you lose nothing.

For most implementations, Option A is cleaner. Create a one-time setup section at the top of your flow or, better yet, run a separate one-time flow that provisions the folder structure.

Note

SharePoint's "Create file" action has a file size limit when the content is passed as inline base64 — typically around 250 MB for SharePoint connectors in standard flows. For most email attachments this is not a concern, but if your use case involves large file attachments (video files, large archives), you'll need to look at chunked upload approaches using the SharePoint REST API via HTTP actions.

Capturing the SharePoint File ID for Later Use

After the "Create file" action, you have access to output properties including ID, ItemId, and Path. Capture these — you need them for the approval flow. Add a Compose action to store the SharePoint item ID:

outputs('Create_file')?['body/ItemId']

Name this Compose something specific like Compose_SharePointItemId. You'll reference this output in your approval action to link the approval to the specific document.

For more patterns on working with files across OneDrive and SharePoint, Copying and Moving Files Automatically with Power Automate: OneDrive, SharePoint, and Local Folder Workflows covers the full range of file manipulation options available.


Content-Based Approval Routing: Going Beyond File Type

Routing by file type alone is blunt. You want to trigger approvals based on what a document contains or signals, not just what format it's in. This is where the design gets sophisticated.

You have several signals available to you without opening the document itself:

The email subject line — Does it contain "Contract," "Agreement," or "Authorization"? The trigger's Subject output is available inside the loop.

The sender's email address — Is this an internal user or an external vendor? A new vendor you've never received email from? You can compare From against a known-safe list in a SharePoint list.

The attachment name — Even before looking at content, filenames like MSA_2024_Acme_Corp.docx or PO_Amendment_v3.pdf carry meaningful signals.

File size — An unusually large PDF might be a contract with exhibits, triggering a different approval chain than a 50KB one-pager.

AI Builder document classification — If you have AI Builder available on your license, you can pass the document content to a trained classification model that returns a document type with confidence scoring.

Let's build a layered condition that uses these signals. After the "Create file" action but still inside the loop, add a Condition action with the following logic:

Condition 1 (AND group): varApprovalRequired is equal to true

AND

One of these sub-conditions (use an OR group):

  • triggerOutputs()?['body/subject'] contains Contract
  • triggerOutputs()?['body/subject'] contains Agreement
  • items('Apply_to_each')?['name'] contains Contract
  • items('Apply_to_each')?['name'] contains MSA
  • items('Apply_to_each')?['name'] contains Amendment

This double-layer check means: approval is required AND either the email subject or the filename suggests this is a legal/contractual document.

Key insight

The triggerOutputs()?['body/subject'] reference works inside a loop because it refers to the trigger that started the flow, which never changes. You're not re-reading the email on each iteration — you're referencing the same trigger payload. This is efficient and correct.

If you want to route different document types to different approvers, this is where you'd branch further. A PDF named invoice.pdf from an email subject of "Invoice Submission" goes to the finance manager. A DOCX named MSA_Acme.docx from an email subject of "Contract for Signature" goes to legal. For detailed patterns on routing to different approvers based on content signals, Building a Dynamic Multi-Condition Approval Flow in Power Automate: Routing Requests to Different Approvers Based on Form Input, Dollar Thresholds, and Department Rules covers this architecture comprehensively.


Triggering the Approval Flow

Inside the "Yes" branch of your approval condition, add a "Start and wait for an approval" action from the Approvals connector.

Configure it as follows:

Approval type: Approve/Reject - First to respond (for single approver) or Approve/Reject - Everyone must approve (for multi-approver chains requiring consensus).

Title: Build a dynamic title that tells the approver what they're looking at:

concat('Review Required: ', items('Apply_to_each')?['name'], ' from ', triggerOutputs()?['body/from'])

Assigned to: This should be a specific email address or a dynamic expression that resolves to the right approver. For now, use a static email. We'll discuss dynamic routing momentarily.

Details: Give the approver everything they need to make a decision without having to open other systems:

concat(
  'A document requiring review has been received and saved to SharePoint.\n\n',
  'File: ', items('Apply_to_each')?['name'], '\n',
  'From: ', triggerOutputs()?['body/from'], '\n',
  'Email Subject: ', triggerOutputs()?['body/subject'], '\n',
  'Received: ', formatDateTime(triggerOutputs()?['body/receivedDateTime'], 'dddd, MMMM d, yyyy h:mm tt'), '\n',
  'SharePoint Location: ', varDestinationFolder, '\n\n',
  'Email Body Preview:\n',
  triggerOutputs()?['body/bodyPreview']
)

Item link: Use the SharePoint file URL from the "Create file" action output: outputs('Create_file')?['body/{Link}']

Item link description: View document in SharePoint

This approval action will pause the flow — the current loop iteration halts and waits for a human response. This is deliberate. It means you can't process attachment number three until attachment number two's approval resolves. This may or may not be acceptable depending on your volume.

Warning

"Start and wait for an approval" is a synchronous, blocking action inside a loop. If you have three attachments that all trigger approvals, they'll be processed sequentially — approval 1 must complete before attachment 2 is even saved to SharePoint. For high-volume scenarios where this would cause unacceptable delays, consider a "Start an approval" (non-waiting) action combined with a separate flow triggered when approvals complete. This decouples the file saving from the approval resolution.

For building more sophisticated approval patterns with parallel tracks and escalation, Designing Multi-Stage Approval Chains in Power Automate: Sequential, Parallel, and Delegated Sign-Off Patterns is the right next read.

Handling the Approval Response

After the approval action, add a Condition to branch on the outcome:

The condition checks: outputs('Start_and_wait_for_an_approval')?['body/outcome'] is equal to Approve

Yes branch: Update the SharePoint file's metadata to mark it as approved. Use the "Update file properties" action from the SharePoint connector, targeting the item ID you captured in the Compose action earlier. Set a "Approval Status" column to "Approved" and an "Approved By" column to outputs('Start_and_wait_for_an_approval')?['body/responder'].

No branch: You have choices. The file is already in SharePoint, so you can:

  • Move it to a "Rejected" subfolder using "Move file" (if that action fits your library setup)
  • Update its metadata to mark it as "Rejected" with the rejection comments from outputs('Start_and_wait_for_an_approval')?['body/responses'][0]['comments']
  • Send a notification email back to the original sender

For most scenarios, updating metadata and notifying the sender is cleaner than moving files, because it preserves the audit trail without creating folder navigation complexity.


Updating the Processed Files Log

At the end of each loop iteration, regardless of file type or approval status, append a summary record to varProcessedFiles. Use the "Append to array variable" action:

{
  "fileName": "@{items('Apply_to_each')?['name']}",
  "fileType": "@{varCurrentFileExtension}",
  "destinationFolder": "@{varDestinationFolder}",
  "approvalRequired": "@{varApprovalRequired}",
  "sharePointItemId": "@{outputs('Create_file')?['body/ItemId']}",
  "processedAt": "@{utcNow()}"
}

This creates a running log that you can use after the loop completes to send a summary email to whoever submitted the original message, confirming exactly which files were saved and where.

After the loop, add a "Send an email (V2)" action back to the original sender:

To: triggerOutputs()?['body/from']

Subject: Re: @{triggerOutputs()?['body/subject']} — Files Processed

Body: Use an HTML body that lists out the contents of varProcessedFiles — but since that's an array and email bodies expect a string, you'll need to convert it. The join function is your friend here, though it works best on simple arrays. For a structured array, use a Select action to transform each entry into a readable line, then join the results.

Alternatively, store this log in a SharePoint list row — one flow run, one list item, with a multi-line text column containing the JSON of the processed files. This creates an auditable record of every email processing event that's queryable, filterable, and reportable. For patterns on managing SharePoint list records as part of automation workflows, Automating SharePoint List Item Lifecycle Management with Power Automate: Creating, Updating, Archiving, and Deleting Records Based on Business Rules goes deep on this pattern.


Handling the "No Attachments" Edge Case

Your trigger is configured to only fire on emails with attachments, so theoretically you'll never process an empty attachments array. But there's a subtle edge case: some email clients send inline images (like email signatures with logos) as attachments with MIME type image/png or image/gif. These will pass the "only with attachments" filter and trigger your flow even when there's no meaningful document attached.

Add a Condition action before the loop that checks whether the attachments array contains anything you actually want to process:

length(triggerOutputs()?['body/attachments'])

If this equals 0, terminate the flow cleanly. But more practically, you should filter out inline images at the loop level — in the Default case of your Switch action (the file types that don't match any known extension), add a check on content type:

if(
  or(
    equals(items('Apply_to_each')?['contentType'], 'image/gif'),
    equals(items('Apply_to_each')?['contentType'], 'image/png'),
    startsWith(items('Apply_to_each')?['contentType'], 'image/')
  ),
  'Skip',
  'Unsorted'
)

If the content type is an image in the Default case (meaning it wasn't a recognized document extension), you can use a Condition to skip the file save entirely and just append a "Skipped: inline image" record to your log.

Tip

Outlook's attachment representation includes an IsInline property in some connector versions. Check whether your trigger version surfaces this — if it does, filtering on IsInline equals false is the cleanest way to exclude signature images and embedded media before you even enter the classification logic.


Hands-On Exercise

Build this flow from scratch against a real SharePoint document library using the following scenario:

Scenario: Your company receives vendor onboarding packets via email. Each packet may contain up to six files: a completed vendor form (PDF), a W-9 (PDF), a bank authorization form (PDF), a business license (PDF or JPG), a sample invoice (Excel), and a vendor agreement (Word). Your flow should:

  1. Save each file to a type-appropriate subfolder within /Vendor Onboarding/[VendorName]/ where [VendorName] is extracted from the email sender's display name
  2. Trigger an approval from the Procurement Manager for any Word documents (vendor agreements)
  3. Trigger a separate approval from the Finance Manager for any Excel files (sample invoices)
  4. Send a confirmation email to the submitting vendor listing all files received

Step 1: Create the trigger with appropriate folder and attachment filters.

Step 2: Initialize all required variables, including one called varVendorName that extracts the sender display name using:

first(split(triggerOutputs()?['body/from'], '<'))

Then use trim(varVendorName) to clean whitespace.

Step 3: Build the Switch on extension. For each case, set the destination folder to include varVendorName:

concat('/Vendor Onboarding/', trim(varVendorName), '/PDFs')

Step 4: Inside the DOCX case, after saving the file, start an approval assigned to the Procurement Manager's email. Inside the XLSX case, start an approval assigned to the Finance Manager's email.

Step 5: After the loop, send the confirmation email using the varProcessedFiles array.

Test it: Send yourself a test email with three dummy attachments — a PDF, an Excel file, and a Word document. Verify that all three land in the right subfolders, the Word and Excel approvals appear in your Approvals center, and the confirmation email arrives with the correct file list.


Common Mistakes and Troubleshooting

"My loop only processes the first attachment"

This almost always means you configured the Apply to Each incorrectly. The input must be the Attachments array from the trigger — specifically the token that represents the whole array, not a property of a single attachment. In the dynamic content panel, look for Attachments under the trigger heading, not inside any other action's outputs. If you accidentally selected a property that evaluates to a single value, Power Automate may implicitly wrap it in a single-item array, so you'll see one iteration rather than the error you'd expect.

"SharePoint Create file fails with 'The specified folder does not exist'"

As discussed, the folder must exist before you write to it. The error message is explicit, but new users miss it because they expect SharePoint to create folders on demand like a filesystem. Add pre-creation logic or use the defensive approach with "Configure run after" on a "Create new folder" action.

"The approval action times out or the flow just stops"

The default timeout for "Start and wait for an approval" is 30 days. After that, the flow resumes with a timed-out outcome, which you can handle in your condition branch. But if approvals are piling up and approvers aren't responding, check whether your approval notification emails are reaching them — sometimes they land in junk. For handling timeouts, escalation, and reminders, Automating Recurring Approval Reminders in Power Automate: Escalating Overdue Requests, Notifying Delegates, and Closing Stale Approvals Automatically covers the full pattern.

"The file content is corrupted in SharePoint"

This happens when you accidentally apply a string transformation to the contentBytes before passing it to Create file. contentBytes is base64-encoded binary — treat it as an opaque blob. Don't trim it, don't concatenate it, don't run it through a Compose that also processes string values. Any string operation on it risks corrupting the binary data. Keep the content bytes reference clean and isolated.

"The extension parser returns the full filename for files without extensions"

Expected behavior. As noted earlier, last(split('README', '.')) returns README. Your Switch Default case will catch this. Decide in the Default case whether to save these files or skip them. For most business email scenarios, attachments without extensions are unusual and probably warrant review — save them to an Unsorted folder and log them.

"My approval fires for every PDF, not just contracts"

You need the content-based condition layer — the subject/filename keyword matching — not just the file type check. Review the section on content-based approval routing. If you set varApprovalRequired = true for all PDFs in the Switch case, then never added a second condition to narrow it down, every PDF will trigger approval. Build the layered condition as described.

Warning

Approvals consume resources — both API calls and approver attention. A flow that sends approval requests for every incoming PDF will desensitize your approvers within days, leading to rubber-stamping or ignored notifications. The goal of content-based routing is surgical precision. When an approval arrives, it should always be meaningful.


Extending the Flow: Advanced Patterns Worth Knowing

Using AI Builder for Richer Content Classification

If your license includes AI Builder, you can pass document content to a pre-trained or custom-trained model that returns structured data about the document. For example, a form processing model trained on invoices can extract vendor name, invoice number, and total amount directly from a PDF. This opens up routing rules like "if invoice amount exceeds $10,000, require CFO approval" — logic that's impossible without reading the document content.

Add an "AI Builder — Extract information from documents" action after saving the file to SharePoint. Pass it the content bytes and the model you've trained. The output includes extracted fields that you can use in your approval condition. For more on integrating AI capabilities into your flows, Building and Deploying Power Automate Flows That Call Azure OpenAI and AI Builder Models covers the full integration pattern.

Chaining Downstream Systems

After files are saved and approved, your flow doesn't have to stop there. You might want to:

  • Create a Planner task assigned to the person responsible for processing the document
  • Post a notification to a Teams channel so the whole team sees that a new vendor contract arrived
  • Update a tracking item in a SharePoint list that powers a Power BI dashboard of incoming document volume

These are all addable actions in the Yes branch of your approval condition or simply after the loop. For the Teams notification pattern, Using Power Automate with Microsoft Teams: Automate Notifications, Approvals, and Channel Messages covers the full range of Teams actions available in the connector.

Applying Managed Metadata Tags

SharePoint document libraries can carry managed metadata columns — term sets that classify documents by type, department, vendor, or business process. After saving a file, you can use the "Update file properties" action to populate these columns based on the classification you've already done in your Switch action. This makes the saved files immediately discoverable through SharePoint's metadata filtering.

The managed metadata column value format is specific — you need to provide both the term's GUID and its label. Getting this right requires understanding how SharePoint term sets are structured. Automating SharePoint and OneDrive Metadata Tagging with Power Automate: Extracting, Classifying, and Applying Managed Metadata at Scale is exactly the resource you need for this extension.


Summary and Next Steps

You've built a flow that does something genuinely complex: it intercepts multi-attachment emails, classifies every file by type, routes each one to the right SharePoint folder with a collision-safe name, and conditionally triggers content-aware approval requests — all without human intervention after the initial setup.

The key architectural decisions we made and why they matter:

Variables over Compose for loop-level state — Variables are settable inside loops; Compose outputs are immutable references. This distinction determines your state management design.

Extension parsing over MIME type trust — Email clients lie about content types. Parsing the filename extension is more reliable for routing decisions.

Collision-safe naming with timestamps and GUIDs — Silent file overwrites are data loss events dressed up as "it worked." Never rely on uniqueness you don't enforce yourself.

Layered content signals for approval routing — File type is a first filter, not a final one. Combining file type with subject line and filename keywords achieves surgical precision without requiring document parsing for every file.

Synchronous vs. asynchronous approvals — "Start and wait" is correct for low-volume flows where you need the approval result to influence subsequent actions. For high-volume scenarios, decouple approval initiation from approval resolution using separate flows.

Where do you go from here? The natural next step is making the approval routing truly dynamic — loading approver assignments from a SharePoint list rather than hardcoding email addresses, so the routing rules can change without touching the flow. After that, consider building the error handling layer: configuring "run after" settings on your critical actions so the flow fails gracefully and notifies an admin when something goes wrong rather than silently dropping documents. For that, Master Error Handling and Retry Patterns in Power Automate for Bulletproof Flows is the essential companion lesson.

Work With Us

From insight to implementation

Reading is the start. When you're ready to build the data, automation, or AI systems behind it, our team turns strategy into shipped results.

Let's Build

Flow Automation Basics

Previous

Automating a Weekly Digest Email with Power Automate: Aggregating SharePoint List Items, Formatting an HTML Table, and Sending a Scheduled Outlook Summary to Your Team

Related Insights

Power AutomatePractitioner

Implementing Power Automate Subscription-Based Webhook Triggers with Azure Event Grid: Registering, Validating, and Renewing Event Subscriptions for Reliable High-Volume Enterprise Event Ingestion

23 min
Power AutomatePractitioner

Automating Excel Workbook Consolidation in Power Automate Desktop: Looping Through Multiple Files, Merging Sheets, and Writing a Combined Output Without Macros

22 min
Power AutomatePractitioner

Automating a Weekly Digest Email with Power Automate: Aggregating SharePoint List Items, Formatting an HTML Table, and Sending a Scheduled Outlook Summary to Your Team

22 min

On this page

  • Introduction
  • Prerequisites
  • Understanding the Architecture Before You Build
  • Setting Up the Trigger: Capturing Emails with Attachments
  • Initializing Variables for State Management
  • Building the Attachment Loop and File Type Classification
  • Extracting the File Extension
  • Building the Classification Condition
  • Generating Collision-Safe Filenames
  • Saving Files to SharePoint with Dynamic Folder Paths
  • Handling Subfolder Creation
  • Capturing the SharePoint File ID for Later Use
  • Content-Based Approval Routing: Going Beyond File Type
  • Triggering the Approval Flow
  • Handling the Approval Response
  • Updating the Processed Files Log
  • Handling the "No Attachments" Edge Case
  • Hands-On Exercise
  • Common Mistakes and Troubleshooting
  • "My loop only processes the first attachment"
  • "SharePoint Create file fails with 'The specified folder does not exist'"
  • "The approval action times out or the flow just stops"
  • "The file content is corrupted in SharePoint"
  • "The extension parser returns the full filename for files without extensions"
  • "My approval fires for every PDF, not just contracts"
  • Extending the Flow: Advanced Patterns Worth Knowing
  • Using AI Builder for Richer Content Classification
  • Chaining Downstream Systems
  • Applying Managed Metadata Tags
  • Summary and Next Steps