How to Auto-Reply to Gmail Emails with Google Apps Script

# How to Auto-Reply to Gmail Emails with Google Apps Script

**Meta Description:** Learn how to build a Gmail auto reply with Google Apps Script. Step-by-step tutorial with full code to automate email responses in minutes.

## Introduction

If your inbox fills up faster than you can respond, you’re not alone. Whether you’re running a small business, managing a side project, or simply going on vacation, missing emails can cost you opportunities and damage relationships. The good news is that **Gmail auto reply with Google Apps Script** gives you a free, flexible, and fully customizable way to automatically respond to incoming emails — no expensive tools or third-party apps required. In this tutorial, you’ll learn exactly how to build this automation from scratch, step by step.

## Prerequisites

Before we dive into the code, make sure you have the following ready:

– **A Google Account** with access to Gmail and Google Drive
– **Basic familiarity with Google Sheets** (we’ll use a Sheet to manage configuration settings)
– **No prior coding experience required** — the code is fully explained with comments
– A few minutes of your time and a willingness to copy, paste, and click

That’s it. Google Apps Script is built into your Google account and requires zero installations.

## What We’re Building

Here’s an overview of what the final automation will do:

1. Scan your Gmail inbox every few minutes using a **time-driven trigger**
2. Look for unread emails that match your criteria (e.g., specific labels or all unread messages)
3. Send an automatic reply from your Gmail account
4. Label the thread so it doesn’t get replied to twice
5. Log each auto-reply in a Google Sheet for your records

This is a clean, reliable system that you control entirely.

## Step 1: Create Your Google Sheet

First, let’s set up the Google Sheet that will act as your control panel and log.

1. Go to [sheets.google.com](https://sheets.google.com) and create a new blank spreadsheet
2. Name it something like **”Gmail Auto Reply Manager”**
3. Set up the following sheet tabs and headers:

**Sheet 1 — “Config”**

| A | B |
|—|—|
| Setting | Value |
| Auto Reply Subject | Re: Thanks for reaching out! |
| Auto Reply Body | Hi there! Thanks for your email. I’ll get back to you within 24 hours. — [Your Name] |
| Label Name | auto-replied |
| Max Emails Per Run | 10 |

**Sheet 2 — “Log”**

| A | B | C | D |
|—|—|—|—|
| Timestamp | From | Subject | Status |

Your Sheet is now ready to serve as both the configuration hub and the activity log.

## Step 2: Open the Apps Script Editor

1. In your Google Sheet, click **Extensions** in the top menu
2. Select **Apps Script**
3. You’ll see a new tab open with the Apps Script editor
4. Delete any default code in the editor (usually a placeholder `myFunction`)
5. You’re now ready to paste in our script

## Step 3: Write the Auto-Reply Script

Copy and paste the following complete script into the Apps Script editor:

“`javascript
// ============================================================
// Gmail Auto Reply Script — Google Apps Script Tutorial
// ============================================================

/**
* Main function: scans inbox for unread emails and sends auto-replies.
* Set this up with a time-driven trigger to run automatically.
*/
function autoReplyToEmails() {
// — Load configuration from the “Config” sheet —
const ss = SpreadsheetApp.getActiveSpreadsheet();
const configSheet = ss.getSheetByName(“Config”);
const logSheet = ss.getSheetByName(“Log”);

// Read settings from the Config sheet (column B, rows 2-5)
const replySubject = configSheet.getRange(“B2”).getValue();
const replyBody = configSheet.getRange(“B3”).getValue();
const labelName = configSheet.getRange(“B4”).getValue();
const maxEmails = configSheet.getRange(“B5”).getValue();

// — Get or create the Gmail label used to track replied threads —
let repliedLabel = GmailApp.getUserLabelByName(labelName);
if (!repliedLabel) {
repliedLabel = GmailApp.createLabel(labelName);
Logger.log(“Created new Gmail label: ” + labelName);
}

// — Search for unread inbox emails that haven’t been auto-replied yet —
// The query uses Gmail search syntax — customize as needed
const query = “is:unread in:inbox -label:” + labelName;
const threads = GmailApp.search(query, 0, maxEmails);

Logger.log(“Found ” + threads.length + ” thread(s) to process.”);

// — Loop through each matching thread —
threads.forEach(function(thread) {
const messages = thread.getMessages();

// Get the most recent message in the thread
const lastMessage = messages[messages.length – 1];
const fromEmail = lastMessage.getFrom();
const subject = lastMessage.getSubject();

// Skip emails sent by yourself to avoid reply loops
const myEmail = Session.getActiveUser().getEmail();
if (fromEmail.indexOf(myEmail) !== -1) {
Logger.log(“Skipping own email: ” + subject);
return; // continue to next thread
}

// — Compose and send the auto-reply —
try {
// Build the subject line (add “Re:” only if not already there)
const autoSubject = subject.startsWith(“Re:”) ? subject : replySubject;

// Reply to the thread (keeps conversation intact in Gmail)
thread.reply(replyBody, {
subject: autoSubject
});

// Apply the label to prevent duplicate replies
thread.addLabel(repliedLabel);

// Mark the thread as read so it’s tidier in your inbox
thread.markRead();

// — Log the action to the Log sheet —
logSheet.appendRow([
new Date(), // Timestamp
fromEmail, // Sender
subject, // Original subject
“Auto-replied” // Status
]);

Logger.log(“Auto-replied to: ” + fromEmail + ” | Subject: ” + subject);

} catch (error) {
// If something goes wrong, log the error instead of crashing
Logger.log(“Error replying to thread: ” + error.message);
logSheet.appendRow([
new Date(),
fromEmail,
subject,
“Error: ” + error.message
]);
}
});

Logger.log(“Auto-reply run complete.”);
}

// ============================================================
// OPTIONAL: Send a custom reply with HTML formatting
// ============================================================

/**
* Advanced version: sends an HTML-formatted auto-reply.
* Replace thread.reply() in the main function with this if needed.
*/
function sendHtmlReply(thread, fromEmail, subject) {
const htmlBody = `

Hi there,

Thank you for reaching out! I’ve received your email and will
respond within 24 hours.

In the meantime, feel free to visit our
FAQ page
for quick answers.

Best regards,
Your Name

`;

GmailApp.sendEmail(fromEmail, “Re: ” + subject, “”, {
htmlBody: htmlBody,
name: “Your Name” // The display name shown to the recipient
});
}

// ============================================================
// SETUP HELPER: Create the time-driven trigger automatically
// ============================================================

/**
* Run this function ONCE to set up an automatic trigger.
* After running it, autoReplyToEmails() will run every 5 minutes.
* WARNING: Do not run this multiple times or you’ll create duplicate triggers.
*/
function createTrigger() {
// Delete any existing triggers for this function first
const triggers = ScriptApp.getProjectTriggers();
triggers.forEach(function(trigger) {
if (trigger.getHandlerFunction() === “autoReplyToEmails”) {
ScriptApp.deleteTrigger(trigger);
}
});

// Create a new time-driven trigger: every 5 minutes
ScriptApp.newTrigger(“autoReplyToEmails”)
.timeBased()
.everyMinutes(5)
.create();

Logger.log(“Trigger created! autoReplyToEmails will run every 5 minutes.”);
}
“`

## Step 4: Authorize the Script

The first time you run the script, Google will ask for permission to access your Gmail and Sheets. Here’s how to handle that:

1. In the Apps Script editor, click **Save** (the floppy disk icon or `Ctrl+S`)
2. From the function dropdown at the top, select **`autoReplyToEmails`**
3. Click the **Run** button (▶)
4. A dialog will appear: click **Review Permissions**
5. Choose your Google account
6. You may see a “Google hasn’t verified this app” warning — click **Advanced**, then **Go to [Project Name] (unsafe)**
7. Click **Allow**

This is normal for personal scripts. Your data stays entirely within your own Google account.

## Step 5: Set Up the Automatic Trigger

Now let’s make the script run automatically so you don’t have to trigger it manually every time.

1. In the function dropdown, select **`createTrigger`**
2. Click **Run**
3. Check the **Executions** log — you should see “Trigger created!”

To verify the trigger was created:
– Click the **clock icon** (Triggers) in the left sidebar of the Apps Script editor
– You should see `autoReplyToEmails` listed with a frequency of “Every 5 minutes”

You can adjust the frequency by modifying `.everyMinutes(5)` in the `createTrigger` function. Options include `.everyMinutes(10)`, `.everyHours(1)`, or `.everyDays(1)`.

## Step 6: Customize Your Auto-Reply

The real power of this setup is how easy it is to customize — without touching the code. Just update the **Config sheet**:

– **Auto Reply Subject**: Change the subject line of your reply
– **Auto Reply Body**: Update your message text any time
– **Label Name**: Use a different Gmail label name if you prefer
– **Max Emails Per Run**: Increase or decrease how many emails are processed each time the script runs (keep this under 20 to stay within Gmail quotas)

### Advanced Customization Ideas

**Filter by sender domain** — add this condition inside the `forEach` loop:
“`javascript
// Only auto-reply to emails from a specific domain
if (!fromEmail.includes(“@yourclientdomain.com”)) {
return;
}
“`

**Filter by keyword in subject**:
“`javascript
// Only auto-reply if subject contains “support”
if (!subject.toLowerCase().includes(“support”)) {
return;
}
“`

**Add a custom signature or footer**:
“`javascript
const fullReplyBody = replyBody + “\n\n—\nSent by Gmail Auto-Reply | Powered by Google Apps Script”;
“`

## Testing and Troubleshooting

### How to Test the Script

1. Send yourself a test email from a different email address (or ask a friend to send one)
2. Make sure the email is in your inbox and unread
3. In Apps Script, select `autoReplyToEmails` from the dropdown and click **Run**
4. Check your **Log sheet** — a new row should appear with the timestamp, sender, and “Auto-replied” status
5. Check the recipient inbox — they should have received your auto-reply

### Common Issues and Fixes

| Problem | Likely Cause | Solution |
|—|—|—|
| No emails being processed | Query not matching | Check Gmail label name spelling in Config sheet |
| Duplicate replies being sent | Label not applied | Make sure `labelName` in Config exactly matches your Gmail label |
| “Authorization required” error | Permissions not granted | Re-run the script and go through the authorization flow again |
| Script runs but nothing happens | No unread emails matching query | Send a test email and verify |
| Trigger not appearing | `createTrigger` not run | Select `createTrigger` from dropdown and run it |

### Checking the Execution Log

In the Apps Script editor, click **Executions** in the left sidebar. This shows every time the script has run, whether it succeeded or failed, and any log messages. This is your best debugging tool.

## Google Apps Script Quotas to Know

Google Apps Script has daily usage limits. For free accounts:

– **Gmail read/write operations**: 20,000 per day
– **Emails sent**: 100 per day (personal Gmail) or 1,500 per day (Google Workspace)
– **Script runtime**: 6 minutes per execution

For most personal use cases, you’ll never hit these limits. If you’re running a high-volume business inbox, consider Google Workspace.

## Conclusion

You’ve just built a fully functional **Gmail auto-reply system using Google Apps Script** — completely free, hosted in your own Google account, and endlessly customizable. No monthly subscription, no third-party data access, no learning curve. With the time-driven trigger in place, your inbox is now covered even when you’re away, busy, or just unavailable.

From here, you can expand this script to:
– Route emails to different reply templates based on subject keywords
– Notify yourself via Google Chat when specific senders write in
– Sync your auto-reply log with a CRM using Google Sheets

The possibilities are wide open. Start with what you’ve built here and layer on features as your needs grow.

**Want a ready-made template?** Skip the setup and get a pre-built Google Sheets template with this automation already configured: [Get the Template](https://gumroad.com/l/gas-templates)

*Have questions or run into an issue? Drop a comment below and I’ll help you troubleshoot. If this tutorial saved you time, consider sharing it with someone who could use it!*

コメント

タイトルとURLをコピーしました