Automate Email Invoice Saving to Nextcloud with n8n

This n8n workflow solves the tedious task of manually downloading email invoice attachments and organizing them in Nextcloud. It automatically extracts attachments from IMAP emails, sanitizes filenames, and uploads them to specific dated folders, saving hours of manual effort and reducing errors.
emailReadImap
function
nextCloud
Learn how to Build this Workflow with AI:
Workflow Identifier: 2377
NODES in Use: EmailReadImap, Function, NextCloud

Press CTRL+F5 if the workflow didn't load.

Visit through Desktop for Best experience

Opening Problem Statement

Meet Sarah, an accountant at a growing company that receives dozens of invoice emails daily. Her job involves downloading each invoice attachment from a dedicated ‘Invoices’ email folder, renaming the files for consistency, and uploading them to her team’s Nextcloud storage organized by date and sender. This process eats up at least two hours every day, multiplies human errors like misplaced or wrongly named files, and delays accounting workflows significantly. Sarah’s frustration is relatable to many who deal with repetitive email attachment management tasks that are critical yet time-consuming.

What This Automation Does

This specific n8n workflow automates Sarah’s entire invoice attachment handling process seamlessly and effectively. When activated, it:

  • Connects to an IMAP email account and reads all emails in the “Invoices” folder.
  • Extracts each attachment from all emails, even multiple attachments per email.
  • Sanitizes and standardizes attachment filenames by removing invalid characters and truncating long names.
  • Organizes files by sender name and email date in Nextcloud, creating date-stamped folders automatically.
  • Uploads the cleaned attachment files to the correct Nextcloud folder based on their email metadata.
  • Reduces manual effort drastically, saving Sarah approximately 10+ hours weekly and virtually eliminating file mismanagement errors.

Prerequisites ⚙️

  • 📧 IMAP Email account configured to access the “Invoices” mailbox.
  • 📁 Nextcloud account with access configured for file uploads.
  • 🔑 Credentials set up in n8n: IMAP email credentials and Nextcloud API credentials.
  • ⏱️ An active n8n instance (cloud or self-hosted via platforms like Hostinger).

Step-by-Step Guide

Step 1: Set Up IMAP Email Node to Read Invoice Emails

In your n8n editor, add an IMAP Email node by clicking “+” → Search for IMAP Email → Select it.

Configure it by selecting your email credentials and setting the parameters:

  • Mailbox: Set to Invoices to target your invoice emails folder.
  • Format: Choose resolved to get attachments and parsed metadata.
  • Options > customEmailConfig: Use the value ['ALL'] to fetch all emails.

Once configured, you should see the node ready to fetch emails from the specified mailbox on execution.

Common mistake: Forgetting to select the correct mailbox will result in fetching no invoices.

Step 2: Add a Function Node to Process and Sanitize Attachments

Add a Function node named Map each attachment.

This node’s functionCode takes each email’s attachments, sanitizes filenames (removes unwanted characters and truncates long names), and formats data for Nextcloud:

const _ = require('lodash')

const sanitize = str => _.chain(str)
  .replace(/[^A-Za-z0-9&.-]/g, '-') // sanitise via whitelist of characters
  .replace(/-(?=-)/g, '') // remove repeated dashes
  .trim('-') // trim any leading/trailing dashes
  .truncate({
    length: 60,
    omission: '-'
  })
  .value()

const result = _.flatMap(items.map(item => {
  return _.values(item.binary).map(file => {
    const filename_parts = file.fileName.split('.')
    const ext = _.slice(filename_parts, filename_parts.length-1)
    const filename_main = _.join(_.dropRight(filename_parts), '.')
    file.fileName = sanitize(filename_main) + '.' + ext
    return {
      json: {
        from: sanitize(item.json.from.value[0].name),
        date: sanitize(new Date(item.json.date).toISOString().split("T")[0])
      }, 
      binary: { file }
    }
  })
}))

return result

You should see each attachment separately mapped and cleaned ready for upload.

Common mistake: Make sure your emails contain attachments; empty emails will cause no output.

Step 3: Configure Nextcloud Node to Upload Files

Add a Nextcloud node and connect it from the Map each attachment node.

Set its parameters:

  • Path: Use an expression to organize files inside folders named by the email date and sender: =Documents/Invoices/{{$json["date"]}}_{{$json["from"]}}_{{$binary.file.fileName}}
  • Binary Data Upload: Set to true.
  • Binary Property Name: Set to file.

Upon execution, the Nextcloud node uploads each sanitized attachment file into its dedicated folder automatically.

Common mistake: Incorrect path expressions can cause files to be misplaced or errors.

Customizations ✏️

  • Change Folder Structure: Modify the Path expression in the Nextcloud node to include client names or project codes if available.
  • Attachment Type Filtering: Use an additional Function or IF node after the IMAP node to filter attachments by filetype, e.g., only PDFs.
  • Add Notification: Integrate an Email or Slack node to notify you when new invoices are uploaded.

Troubleshooting 🔧

Problem: “No attachments found in the email”

Cause: Email messages are empty or do not contain attachments accessible by the IMAP node.

Solution: Check your email mailbox for emails with attachments and validate IMAP permissions.

Problem: “Nextcloud upload failed”

Cause: Invalid authentication or incorrect file path in the Nextcloud node.

Solution: Verify your Nextcloud credentials and ensure your path expression in the node is correct.

Pre-Production Checklist ✅

  • Test IMAP connection and fetch one or two emails with attachments successfully.
  • Validate Function node outputs sanitized filenames and correct JSON metadata.
  • Test Nextcloud node uploads files in correct paths as expected.
  • Review your folder structure and naming conventions to avoid conflicts.

Deployment Guide

Activate the workflow by toggling it ON in n8n once configured and tested.

Schedule the execution or trigger manually as needed.

Monitor execution logs in n8n to ensure files are processed and uploaded without errors.

Conclusion

By following this detailed guide, you have automated the tedious and error-prone task of processing email invoices and filing them into Nextcloud. This saves hours weekly and minimizes risks of misfiling important documents. Next steps could involve adding automated invoice data extraction into spreadsheets, invoice payment reminders, or integration with accounting software for end-to-end automation of your finance ops. Keep exploring n8n’s nodes to further ease your workload!

Related Workflows

Automate Viral UGC Video Creation Using n8n + Degaus (Beginner-Friendly Guide)

Learn how to automate viral UGC video creation using n8n, AI prompts, and Degaus. This beginner-friendly guide shows how to import, configure, and run the workflow without technical complexity.
Form Trigger
Google Sheets
Gmail
+37
Free

AI SEO Blog Writer Automation in n8n (Beginner Guide)

A complete beginner guide to building an AI-powered SEO blog writer automation using n8n.
AI Agent
Google Sheets
httpRequest
+5
Free

Automate CrowdStrike Alerts with VirusTotal, Jira & Slack

This workflow automates processing of CrowdStrike detections by enriching threat data via VirusTotal, creating Jira tickets for incident tracking, and notifying teams on Slack for quick response. Save hours daily by transforming complex threat data into actionable alerts effortlessly.
scheduleTrigger
httpRequest
jira
+5
Free

Automate Telegram Invoices to Notion with AI Summaries & Reports

Save hours on financial tracking by automating invoice extraction from Telegram photos to Notion using Google Gemini AI. This workflow extracts data, records transactions, and generates detailed spending reports with charts sent on schedule via Telegram.
lmChatGoogleGemini
telegramTrigger
notion
+9
Free

Automate Email Replies with n8n and AI-Powered Summarization

Save hours managing your inbox with this n8n workflow that uses IMAP email triggers, AI summarization, and vector search to draft concise replies requiring minimal review. Automate business email processing efficiently with AI guidance and Gmail integration.
emailReadImap
vectorStoreQdrant
emailSend
+12
Free

Automate Email Campaigns Using n8n with Gmail & Google Sheets

This n8n workflow automates personalized email outreach campaigns by integrating Gmail and Google Sheets, saving hours of manual follow-up work and reducing errors in email sequences. It ensures timely follow-ups based on previous email interactions, optimizing communication efficiency.
googleSheets
gmail
code
+5
Free