Google Apps Script for Gmail: Comprehensive Guide

Google Apps Script for Gmail: Comprehensive Guide

Google Apps Script allows you to automate Gmail tasks such as sending emails, managing labels, and searching messages. This guide provides step-by-step instructions, code examples, and exercises for mastering Gmail automation with Apps Script.

What is Google Apps Script for Gmail?

Google Apps Script provides access to Gmail features via the GmailApp service, enabling you to:

  • Send emails programmatically.
  • Search and manage messages.
  • Automate email workflows.

How to Use Google Apps Script with Gmail

  1. Open the Apps Script Editor.
  2. Write your Gmail-related script.
  3. Save and authorize the script to access your Gmail account.

Key GmailApp Methods

  1. GmailApp.sendEmail(): Send an email.
  2. GmailApp.getMessagesForThreads(): Access messages in a thread.
  3. GmailApp.search(): Search emails.
  4. GmailApp.createLabel(): Create Gmail labels.

Basic Examples

Example 1: Send an Email

function sendEmail() {

  GmailApp.sendEmail(“recipient@example.com”, “Subject Line”, “This is the email body.”);

}

Explanation:

  • sendEmail(email, subject, body): Sends an email with the specified recipient, subject, and body.

Example 2: Search Emails

function searchEmails() {

  const threads = GmailApp.search(“from:someone@example.com”);

  const messages = GmailApp.getMessagesForThreads(threads);

  Logger.log(`Found ${messages.length} threads.`);

}

Explanation:

  • search(query): Searches emails using a Gmail search query.
  • getMessagesForThreads(threads): Retrieves messages from the found threads.

Example 3: Add a Label to Emails

function labelEmails() {

  const threads = GmailApp.search(“subject:Important”);

  const label = GmailApp.createLabel(“Important”);

  threads.forEach((thread) => thread.addLabel(label));

}

Explanation:

  • createLabel(name): Creates a Gmail label.
  • addLabel(label): Adds the label to a thread.

Advanced Examples

Example 4: Send a Styled Email (HTML)

function sendHtmlEmail() {

  const htmlBody = `

    <h1>Welcome!</h1>

    <p>This is an HTML email sent via Apps Script.</p>

  `;

  GmailApp.sendEmail(“recipient@example.com”, “Styled Email”, “”, {

    htmlBody: htmlBody

  });

}

Explanation:

  • The htmlBody option allows you to send an HTML-formatted email.

Example 5: Auto-Reply to Emails

function autoReply() {

  const threads = GmailApp.search(“is:unread”);

  threads.forEach((thread) => {

    const message = thread.getMessages()[0];

    GmailApp.sendEmail(message.getFrom(), “Re: ” + thread.getFirstMessageSubject(), “Thank you for your email. I’ll get back to you shortly.”);

    thread.markRead();

  });

}

Explanation:

  • getMessages(): Retrieves messages in a thread.
  • markRead(): Marks a thread as read.

Example 6: Delete Spam Emails

function deleteSpam() {

  const threads = GmailApp.search(“label:spam”);

  threads.forEach((thread) => thread.moveToTrash());

}

Explanation:

  • moveToTrash(): Moves a thread to the trash folder.

Exercises

Exercise 1: Send a Custom Email

Write a script to send a personalized email to a recipient with their name in the subject and body.

Solution:

function sendCustomEmail() {

  const name = “John”;

  GmailApp.sendEmail(“recipient@example.com”, `Hello, ${name}!`, `Dear ${name}, this is a personalized email.`);

}

Exercise 2: Count Unread Emails

Write a script to count the number of unread emails in your inbox and log it.

Solution:

function countUnreadEmails() {

  const threads = GmailApp.search(“is:unread”);

  Logger.log(`You have ${threads.length} unread emails.`);

}

Exercise 3: Organize Emails by Date

Write a script to label emails received in the last 7 days as “Recent.”

Solution:

function labelRecentEmails() {

  const label = GmailApp.createLabel(“Recent”);

  const threads = GmailApp.search(“newer_than:7d”);

  threads.forEach((thread) => thread.addLabel(label));

}

Multiple-Choice Questions

Question 1:

Which method is used to send an email?

  1. GmailApp.mail()
  2. GmailApp.send()
  3. GmailApp.sendEmail()
  4. GmailApp.sendMail()

Answer: 3. GmailApp.sendEmail()

Question 2:

What does GmailApp.search(“is:unread”) do?

  1. Finds all unread emails.
  2. Deletes unread emails.
  3. Marks unread emails as read.
  4. Labels unread emails.

Answer: 1. Finds all unread emails.

Question 3:

Which of the following is NOT a valid GmailApp method?

  1. createLabel()
  2. moveToTrash()
  3. addStar()
  4. addPriority()

Answer: 4. addPriority()
Explanation: GmailApp does not have an addPriority() method.

Advanced Example: Email Digest Generator

function sendEmailDigest() {

  const threads = GmailApp.search(“newer_than:1d”);

  let digestContent = “Today’s Email Digest:\n\n”;

  threads.forEach((thread) => {

    const subject = thread.getFirstMessageSubject();

    const sender = thread.getMessages()[0].getFrom();

    digestContent += `From: ${sender}, Subject: ${subject}\n`;

  });

  GmailApp.sendEmail(“recipient@example.com”, “Daily Email Digest”, digestContent);

}

Explanation:

  • Collects emails from the last day.
  • Generates a summary of senders and subjects.
  • Sends the summary to a specified recipient.

Best Practices

  1. Test Scripts Carefully: Ensure scripts handle edge cases, especially for automated email sending.
  2. Use Labels: Organize emails effectively with labels.
  3. Limit Search Queries: Avoid overly broad searches to minimize execution time.