Gmail CSV Attachment to Google Sheets, Automatically
Plenty of reports still arrive by email: a supplier's stock file every morning, a weekly sales export, a bank or payment report your system sends as a CSV attachment. Copying each one into Google Sheets by hand gets old quickly. The free way to automate it is Google Apps Script, which can read Gmail and write to Sheets, and can run on a timer.
Below is a script that does this carefully: it only looks at emails you've labelled, appends rows instead of overwriting, keeps a log so the same attachment is never imported twice, and stays well inside Google's limits. After that we cover where this approach struggles, mostly with messy files, and what to do about it.
What you need
- A Google account with Gmail and Google Sheets. The script runs as you, so it can only read your own mailbox.
- A Google Sheet to receive the data. Create a new one; the script adds a Data tab and an Import log tab.
- Emails that carry the CSV as an attachment. If your report arrives as a download link instead, this script won't see it.
- About fifteen minutes.
Step 1: label the emails with a Gmail filter
The script looks for a Gmail label rather than guessing which emails matter. In Gmail, create a filter that matches the report emails, for example by sender and has:attachment filename:csv, and set it to apply the label csv-import. Gmail's search operators (label:, has:attachment, filename:) are listed in Google's Gmail search operator help. Gmail's help explains how to create a filter. For emails that arrived before the filter existed, select them and add the label by hand.
Keep the label name short and without spaces or slashes, because the script searches for it by name.
Step 2: add the Apps Script
In your Google Sheet, open Extensions > Apps Script, delete the placeholder code, and paste the script below. It uses only built-in services: GmailApp to read mail, SpreadsheetApp to write rows, LockService so two runs never overlap, and Utilities.parseCsv to split the CSV into rows (Utilities reference).
// Settings: change these to suit you.
const SOURCE_LABEL = 'csv-import'; // Gmail label on the emails to import
const DONE_LABEL = 'csv-imported'; // added after a conversation is processed
const DATA_SHEET = 'Data'; // tab that receives the rows
const LOG_SHEET = 'Import log'; // one row per attachment: the duplicate guard
const MAX_THREADS = 10; // conversations per run (keeps runs short)
const MAX_BYTES = 5 * 1024 * 1024; // skip attachments over 5 MB
const TIME_BUDGET_MS = 4 * 60 * 1000; // stop early; Apps Script allows 6 minutes
function importCsvAttachments() {
const lock = LockService.getScriptLock();
if (!lock.tryLock(10 * 1000)) return; // the previous run is still working
try {
const started = Date.now();
const ss = SpreadsheetApp.getActiveSpreadsheet();
const data = ss.getSheetByName(DATA_SHEET) || ss.insertSheet(DATA_SHEET);
const log = ss.getSheetByName(LOG_SHEET) || ss.insertSheet(LOG_SHEET);
if (log.getLastRow() === 0) {
log.appendRow(['Message ID', 'Attachment', 'Email date', 'Rows', 'Result', 'Logged at']);
}
const seen = new Set();
if (log.getLastRow() > 1) {
log.getRange(2, 1, log.getLastRow() - 1, 2).getValues()
.forEach((r) => seen.add(r[0] + '|' + r[1]));
}
const source = GmailApp.getUserLabelByName(SOURCE_LABEL);
if (!source) throw new Error('Create the Gmail label "' + SOURCE_LABEL + '" first.');
const done = GmailApp.getUserLabelByName(DONE_LABEL) || GmailApp.createLabel(DONE_LABEL);
const threads = GmailApp.search('label:' + SOURCE_LABEL + ' has:attachment', 0, MAX_THREADS);
for (const thread of threads) {
for (const message of thread.getMessages()) {
for (const att of message.getAttachments()) {
const name = att.getName();
if (!/\.csv$/i.test(name)) continue;
const key = message.getId() + '|' + name;
if (seen.has(key)) continue;
if (Date.now() - started > TIME_BUDGET_MS) return; // next run carries on
const result = importOne(data, att, name, message.getId());
log.appendRow([message.getId(), name, message.getDate(), result.rows, result.note, new Date()]);
seen.add(key);
}
}
// Moving the conversation off the source label keeps the next search small.
// If a new email lands in the same conversation, your filter labels it
// again and the log stops the old attachments being imported twice.
thread.removeLabel(source);
thread.addLabel(done);
}
} finally {
lock.releaseLock();
}
}
function importOne(sheet, att, name, messageId) {
if (att.getSize() > MAX_BYTES) return { rows: 0, note: 'Skipped: file too large' };
let text = att.getDataAsString('UTF-8');
if (text.indexOf('\uFFFD') !== -1) {
text = att.getDataAsString('windows-1252'); // not valid UTF-8: try the usual Excel encoding
}
text = text.replace(/^\uFEFF/, ''); // drop a byte-order mark
const firstLine = text.split(/\r?\n/, 1)[0];
const delimiter = firstLine.split(';').length > firstLine.split(',').length ? ';' : ',';
const rows = Utilities.parseCsv(text, delimiter)
.filter((r) => r.some((cell) => String(cell).trim() !== ''));
if (rows.length < 2) return { rows: 0, note: 'Skipped: no data rows' };
const header = rows[0].concat(['Source file', 'Source message']).map(safeCell);
const width = header.length;
if (sheet.getLastRow() === 0) {
sheet.getRange(1, 1, 1, width).setNumberFormat('@').setValues([header]);
} else {
const current = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0].map(String);
if (current.join('\u0001') !== header.join('\u0001')) {
return { rows: 0, note: 'Skipped: columns differ from the ' + DATA_SHEET + ' tab' };
}
}
const body = [];
for (let i = 1; i < rows.length; i++) {
const row = rows[i];
if (row.length > width - 2) {
return { rows: 0, note: 'Skipped: line ' + (i + 1) + ' has more cells than the header' };
}
const padded = row.concat(new Array(width - 2 - row.length).fill(''));
body.push(padded.concat([name, messageId]).map(safeCell));
}
// Plain-text format keeps leading zeros and stops Sheets guessing dates.
sheet.getRange(sheet.getLastRow() + 1, 1, body.length, width)
.setNumberFormat('@')
.setValues(body);
return { rows: body.length, note: 'Imported' };
}
// Sheets treats a value that starts with "=" as a formula. Prefix risky cells
// with an apostrophe so they stay text. Plain amounts like -12.50 are untouched.
function safeCell(value) {
const s = String(value);
if (/^\s*=/.test(s) || (/^\s*[+\-@]/.test(s) && /[A-Za-z]/.test(s))) return "'" + s;
return s;
}
// Run once by hand to schedule the import every hour.
function installHourlyTrigger() {
ScriptApp.getProjectTriggers()
.filter((t) => t.getHandlerFunction() === 'importCsvAttachments')
.forEach((t) => ScriptApp.deleteTrigger(t));
ScriptApp.newTrigger('importCsvAttachments').timeBased().everyHours(1).create();
}Save, then choose importCsvAttachments in the function list and click Run. Google asks you to authorise access to Gmail and Sheets the first time; GmailApp methods need the full https://mail.google.com/ scope (GmailApp reference), so the warning screen will mention reading and changing your mail. Check the Data and Import log tabs, then run installHourlyTrigger once to schedule it.
We tested this logic against simulated Gmail and Sheets objects, not against a live Gmail account. Try it on a copy of your sheet with one or two labelled emails first, and check the Import log tab after the first scheduled run.
How the script avoids duplicates and partial imports
The most common complaint about Gmail-to-Sheets scripts is duplicate rows, because the same email gets read every time the script runs. This one uses two guards:
- The Import log tab is the source of truth. Every attachment it handles gets a row with the Gmail message ID and file name, and anything already in the log is skipped.
- After a conversation is processed, the script moves it from the csv-import label to csv-imported. That keeps each search small. If a new report lands in the same conversation (Gmail groups emails with the same subject), your filter labels it again, the conversation comes back, and the log makes sure only the new attachment is imported.
It also refuses to guess when a file doesn't fit. If an attachment's columns differ from the Data tab's header, or a line has more cells than the header, the file is skipped and the reason is written to the log instead of the rows being cut or shifted. Every imported row carries its source file name and message ID in two extra columns, so you can trace or remove a bad batch later.
The limits you'll run into
| Limit | Consumer account | Google Workspace account |
|---|---|---|
| Script runtime | 6 min per execution | 6 min per execution |
| Total trigger runtime | 90 min per day | 6 hr per day |
| Email read/write (excluding send) | 20,000 per day | 50,000 per day |
| Triggers | 20 per user per script | 20 per user per script |
Figures are from Apps Script quotas, and Google notes they can change without notice. The script stops itself after about four minutes and handles at most ten conversations per run, then carries on in the next run, so an hourly trigger uses a small part of the daily budget. Time-driven triggers start at a slightly randomised time within the hour, and if a run fails Google emails you a summary (Installable triggers). A Google Sheet also has a size ceiling: up to 20 million cells (Google Drive file limits). A daily file of 2,000 rows by 15 columns adds about 11 million cells a year, so plan to archive the Data tab.
Where the script struggles: messy CSV files
The script moves data faithfully. It doesn't fix it, and emailed reports are often messy. These are the problems we see most, and what the script does with each:
| Problem in the attachment | What happens | Fix |
|---|---|---|
| Saved by Excel on Windows (not UTF-8) | The script retries as Windows-1252, which covers most Western European text | See fixing weird characters in CSVs |
| Byte-order mark at the start | Removed, so the first header isn't polluted | Background in UTF-8 BOM and CSV encoding |
| Semicolon-separated (European exports) | Detected from the first line | Decimal commas stay as text; see converting European number formats |
| Report title or totals above the header | Columns no longer match, so the file is skipped | Strip them first: removing report headers and footers |
| Leading zeros (SKUs, ZIP codes, account numbers) | Kept, because cells are written as plain text | Why it matters: stop Excel removing leading zeros |
| Cells that start with = (formula-like) | Prefixed with an apostrophe so Sheets doesn't run them as formulas | The apostrophe may show in the cell; that's deliberate |
| Same rows sent twice in different emails | Imported twice (the log only stops the same attachment) | Remove them later: removing duplicate rows |
| Columns renamed or reordered by the sender | Skipped with a log entry | Rename the columns, or start a new Data tab |
Because everything is written as text, numbers and dates won't sort or sum as numbers until you convert the columns (Format > Number in Sheets). That is the safe default: converting automatically is exactly how leading zeros and day/month dates get mangled.
Cleaning the CSV before it goes into Google Sheets
If the files you're sent need more than the script can safely do, clean them first. PipeSheets is a file cleaner: you upload a CSV or XLSX, run a preset or your own saved pipeline, preview every change, and download the cleaned file. It doesn't connect to Gmail or write into Google Sheets, so for a recurring report the honest workflow today is: save the attachment, upload it to PipeSheets, download the cleaned CSV, then import it (File > Import in Sheets) or send it through the script above.
Steps that fix the problems in the table above:
- Remove footer rows such as totals and disclaimers. Lines above the real header need deleting before upload, because PipeSheets reads the first row as the header.
- Trim spaces, fix curly quotes and odd spaces, and blank out placeholders like N/A (Quick Clean does the first and last of these).
- Convert dates to one format, and money like $1,234.56 or (50.00) into plain numbers.
- Rename and reorder columns to match the sheet you're appending to.
- Remove duplicate rows.
Save the steps as a pipeline and each new file is a single run. Supplier price lists are the classic case, see the vendor catalog CSV cleaner, and if you're cleaning a batch of files every month, setting up a monthly CSV cleanup pipeline shows how to keep it repeatable.
Other ways to do this
- No-code automation tools (Zapier, Make, n8n and similar) can watch Gmail and add rows to Sheets. They are easier to set up but usually have their own task or file-size limits and pricing; check their current docs.
- If the sender can put the file somewhere instead of emailing it, a shared Google Drive folder is easier to automate than an inbox.
- If the report comes from a system with an API, pulling the data directly avoids the CSV step altogether.
Quick answers
Can Google Sheets import a CSV from Gmail without a script?
Not automatically. You can download the attachment and use File > Import, but a scheduled import from Gmail needs Apps Script or a third-party tool.
Will this overwrite my sheet each time?
No. This version appends to the Data tab. Many published examples clear the sheet first; that's fine for a single "latest report" tab, but you lose history.
What if the email has an XLSX attachment instead?
This script ignores anything that isn't a .csv file. Excel files need converting first; see converting Excel to CSV UTF-8.
The script gets the file into Sheets; clean data is a separate job. If your emailed reports need that second step, create a free PipeSheets account and clean your first file: upload it, check the preview, and download a CSV that imports cleanly.
Related guides
- How to Clean an Excel Contact List for Mail Merge (Word and Gmail)Mail merge failures almost always trace back to the spreadsheet, not Word or Gmail. Here is exactly how to clean your contact list so every letter and email comes out right the first time.
- AI Data Cleaning Tool for Excel: Copilot vs Formulas vs a Dedicated CleanerLooking for an AI data cleaning tool for Excel? Start with one fact: the =COPILOT() cell function was retired on September 14, 2026. Here is what is actually available now, when AI helps, when formulas and Power Query are the better tool, and what a dedicated cleaner adds.
- Salesforce Account and Contact Update CSVs: Matching by Email, ID, or External IDUpdating existing Salesforce records with a CSV comes down to one decision: which match key ties each row to the right record. This guide covers matching by Salesforce ID, email, or external ID, and how to preflight the file so you don't create duplicate contacts.
- HubSpot Contacts + Companies Import: Clean One-Sheet Files, Headers, IDs, and DomainsImporting contacts and companies together in HubSpot fails on the same handful of file problems: multiple sheets, headers that don't match properties, and missing dedupe keys. Here's how to prep the file so records create, update, and associate on the first try.
Try the automated solution
PipeSheets can fix these issues automatically. Create a free account to clean your first file.
Create a free accountOr see how it works: Vendor Catalog CSV Cleaner