Excelgoodies logo +40 31 2299227

LEARN THIS HANDS ON

Power Apps & Power Automate

. Live Online FILLING FAST
View all upcoming batches
ANAF Deletes Your e-Factura After 60 Days: The Power Automate Flow That Saves Them

ANAF Deletes Your e-Factura After 60 Days: The Power Automate Flow That Saves Them

Most Romanian finance teams have already hit this: you go back to ANAF’s e-Factura portal for an invoice from three months ago and it’s gone. ANAF only guarantees access for a limited period, and the portal is not your archive. This article shows a concrete Power Automate flow that automatically downloads and stores every e-Factura XML so you keep control of your own history.

The Scenario: Shared Inbox, Vanishing XMLs

You have a shared mailbox (e.g. facturi@company.ro) where suppliers send e-Factura attachments. Your accounting app doesn’t yet integrate directly with ANAF’s API, so the XMLs in that mailbox are your lifeline.

Pain points:

  • ANAF’s portal only keeps invoices accessible for a limited time (commonly treated as ~60 days in practice).
  • Audits or reconciliations often need invoices older than that.
  • Manual download and filing of XMLs is error-prone and never fully done.

Target state:

  • Every e-Factura email that lands in the shared inbox is processed automatically.
  • XML attachments are saved to a structured archive in SharePoint or OneDrive.
  • You can rebuild any period’s invoices from your own archive, independent of ANAF’s retention.

We’ll build a single cloud flow in Power Automate that:

  1. Triggers when new emails arrive in the shared mailbox.
  2. Filters to e-Factura messages.
  3. Extracts the XML attachment(s).
  4. Saves them to a SharePoint document library with a predictable naming convention.

Design Choices: Where and How to Archive

Before building the flow, decide:

1. Storage Target

Most teams will pick one of:

  • SharePoint document library (recommended for teams):
    • Versioning, retention labels, and access control per site.
    • Easy integration with Power BI and Power Query.
  • OneDrive for Business (OK for small teams):
    • Simple setup, but ownership is tied to a user account.

We’ll use SharePoint in the example, with a library like e-Factura-Archive on a finance site.

2. File Naming Strategy

You want deterministic, unique file names that help later processing. A robust pattern:

{SupplierName}_{InvoiceNumber}_{IssueDate:yyyyMMdd}_{OriginalFileName}.xml

If you can’t reliably parse supplier or invoice number from the XML today, at minimum:

{ReceivedDate:yyyyMMddHHmmss}_{MessageId}_{OriginalFileName}.xml

We’ll implement the second pattern, because it only relies on email metadata.

3. Trigger Scope

Options for the email trigger:

  • “When a new email arrives (V3)” – Outlook: for user mailboxes.
  • “When a new email arrives in a shared mailbox (V2)” – Outlook: for shared inboxes.

We’ll build on the shared mailbox trigger to match the usual facturi@ pattern.

Building the Flow: Step-by-Step

Assumptions:

  • You have a shared mailbox in Exchange Online.
  • You have a SharePoint site (e.g. https://tenant.sharepoint.com/sites/Finance) with a document library e-Factura-Archive.
  • You have permission to create flows and access both resources.

Step 1 – Create the Flow and Add the Trigger

  1. Go to Power Automate > My flows > New flow > Automated cloud flow.
  2. Name it: Archive e-Factura from Shared Mailbox.
  3. Search for Outlook and select When a new email arrives in a shared mailbox (V2).
  4. Configure:
    • Shared mailbox address: facturi@company.ro (your actual address).
    • Folder: usually Inbox.
    • Include Attachments: Yes.
    • Only with Attachments: Yes (reduces noise).
    • Importance: Any.

This trigger fires whenever a new email with attachments hits the shared inbox.

Step 2 – Filter to e-Factura Emails

You don’t want to archive every attachment; only e-Factura XMLs.

Common patterns for e-Factura messages:

  • Subject contains e-Factura.
  • Body contains ANAF-specific text.
  • Attachments are XML files, often with specific naming conventions.

We’ll filter based on subject and XML attachments.

  1. Add a Condition action.
  2. In the Condition, set:
    • Left side: Subject (from the trigger).
    • Operator: contains.
    • Right side: e-Factura.

This is a simple first filter. If your suppliers use different wording, adjust the condition to match your reality.

Under the If yes branch, we’ll process attachments. Under If no, we do nothing.

Step 3 – Loop Through Attachments

In the If yes branch:

  1. Add an action: Apply to each.
  2. For the Select an output from previous steps, pick the trigger’s Attachments array.

Inside the Apply to each, you now have one context per attachment, with properties like Name and ContentBytes.

Step 4 – Filter to XML Attachments Only

Inside the Apply to each:

  1. Add a Condition action.
  2. Configure:
    • Left side: Name (attachment name).
    • Operator: ends with.
    • Right side: .xml.

Under If yes, we’ll save the file. Under If no, we skip the attachment (e.g. PDF, ZIP).

Step 5 – Build a Robust File Name

We’ll use:

{ReceivedDate:yyyyMMddHHmmss}_{MessageId}_{OriginalFileName}.xml

The values we need:

  • ReceivedDateTime from the email trigger.
  • MessageId from the email trigger.
  • Name from the attachment.

Power Automate expressions let us format the date and concatenate strings.

Expression for Received Date

In a text field, click Expression and use:

formatDateTime(triggerOutputs()?['body/receivedDateTime'], 'yyyyMMddHHmmss')

This returns a sortable timestamp like 20261031153042.

Expression for Message ID

Message ID can contain characters not ideal for file names. A simple approach is to remove angle brackets and @.

Add a Compose action before the XML condition (still inside the Apply to each), named Sanitized Message Id with this expression:

replace(replace(replace(triggerOutputs()?['body/messageId'], '<', ''), '>', ''), '@', '_')

This gives you a safer identifier.

Build the Final Name

Inside the If yes branch of the XML condition, add another Compose action named Final File Name:

concat(
  formatDateTime(triggerOutputs()?['body/receivedDateTime'], 'yyyyMMddHHmmss'),
  '_',
  outputs('Sanitized Message Id'),
  '_',
  items('Apply_to_each')?['Name']
)

Note: Power Automate auto-generates names like Apply_to_each. Use the exact names from your flow or adjust the expression via the dynamic content picker to avoid typos.

Step 6 – Save the XML to SharePoint

Now we can create the file in SharePoint.

Inside the If yes branch of the XML condition:

  1. Add a Create file action from the SharePoint connector.
  2. Configure:
    • Site Address: your finance site (e.g. https://tenant.sharepoint.com/sites/Finance).
    • Folder Path: /e-Factura-Archive (pick from the browser UI).
    • File Name: use the output of Final File Name compose.
    • File Content: use the attachment’s ContentBytes.

This stores the XML exactly as received.

Step 7 – Avoid Duplicate Files (Optional but Useful)

If suppliers resend the same invoice, you may want to avoid duplicate archives.

A simple deduplication approach:

  • Before Create file, add Get file metadata using path.
  • Use the same Final File Name for the path.
  • If the file exists, skip creation.

Because file existence checks require careful error handling (404 vs. other errors), a safer pattern is:

  1. Add Get files (properties only) on the library with a Filter Query on FileLeafRef equal to your target name.
  2. Add a Condition: if the result array length is 0, then create file; otherwise, skip.

The exact OData filter depends on your library setup. For many teams, accepting duplicates is fine because the timestamp and message ID will differ.

Security and Compliance Considerations

You’re moving tax-relevant documents into your own archive. A few points matter:

  • Permissions: Ensure the SharePoint library is restricted to finance and audit roles.
  • Retention: Use Microsoft Purview retention policies or SharePoint retention labels if your organization requires specific retention periods.
  • Access from Power BI / Power Query: If you later consume these XMLs, ensure data models are secured separately from the raw archive.

The flow itself runs under the credentials of the owner or the connection reference used. Make sure the account has least-privilege access: shared mailbox and target library, nothing more.

Monitoring and Error Handling

Power Automate flows fail. For something as critical as your e-Factura archive, you want visibility.

Recommended additions:

  1. Configure run-after on key actions:
    • If Create file fails, send a notification email to the finance admin group.
  2. Add a failure branch:
    • Use a Scope to group all main actions.
    • Add another Scope named On Error.
    • Configure On Error to run after the main scope on has failed, has timed out, or has skipped.
    • In On Error, send an email with the subject and message ID of the failed item.
  3. Turn on flow analytics:
    • Use Power Automate’s built-in analytics to watch failure rates and throughput.

Adapting the Flow for Direct ANAF API Integration

Some teams will eventually integrate directly with ANAF’s e-Factura API to pull invoices, not just email attachments. The pattern above still helps:

  • The archive library remains the same.
  • Instead of the Outlook trigger, you use an HTTP or custom connector trigger to fetch invoices.
  • The Create file step is identical.

The key idea: whatever your upstream source (email, API, ERP export), Power Automate is the orchestrator that writes XMLs into a durable, queryable archive.

Practical Takeaway: Make the Archive Boring and Automatic

If ANAF deletes your e-Factura invoices after around 60 days, your archive must be more reliable than someone remembering to click “Download XML”. The practical move is to set up one Power Automate flow that:

  • Watches the shared mailbox.
  • Filters to e-Factura emails.
  • Saves every XML to a controlled SharePoint library with deterministic names.

Once this is in place and monitored, the “we can’t find the XML anymore” conversation disappears, and you regain control over your own invoice history.

Editor's Note

This article reflects the shift from manual e-Factura downloads to automated, SharePoint-based archiving using Power Automate, particularly relevant for finance teams relying on shared mailboxes and needing reliable long-term invoice retention beyond ANAF’s portal limits.

Professionals who want to apply these patterns to their own data can explore Excelgoodies' Power Automate Course programme - taught live by instructors, with certification awarded once a real project is running at work.

Insights compiled through ongoing industry research and discussions within the Excelgoodies Analytics Community.

Power Automate

New

Next Batches Now Live

Power BIPower BI
SQLSQL
Power AppsPower Apps
Power AutomatePower Automate
Microsoft FabricMicrosoft Fabrics
AzureAzure Data Engineering
Explore Dates & Reserve Your Spot → Reserve Your Spot →