Google Apps Script: Gmail Email Sending Function Code

As the digital workspace expands, professionals and organizations increasingly rely on automation to streamline everyday tasks. One of the most valuable yet underutilized tools available for users of Google’s ecosystem is Google Apps Script. Specifically, the ability to automate email sending through Gmail using Apps Script can save countless hours and reduce the margin for error. If you manage schedules, send reminders, or distribute reports, automating email delivery can significantly improve efficiency and consistency.

In this guide, we’ll take a serious and trustworthy dive into how you can write a reliable, flexible Gmail email-sending function using Google Apps Script. Whether you’re new to scripting or have prior experience, this article will provide structured code examples, best practices, and practical use cases.

What is Google Apps Script?

Google Apps Script is a cloud-based scripting language based on JavaScript. It allows users to add functionality, automate tasks, and integrate with other Google Workspace services like Gmail, Sheets, Calendar, and Drive. Apps Script runs on Google’s servers, and you don’t need any installation or configuration—if you have a Google account, you’re ready to start scripting.

Why Automate Gmail Email Sending?

There are numerous reasons why automating email sending through Gmail is not only convenient but often necessary:

  • Efficiency: Automatically deliver multiple emails without user input.
  • Reliability: Reduce the chance of human error and ensure timely notifications.
  • Scalability: Easily extend functionality to send emails to dozens or even thousands of recipients.
  • Customization: Use data from Google Sheets or other sources to personalize email content.

Getting Started: Accessing Google Apps Script

Before diving into the code, let’s set up your development environment:

  1. Go to script.google.com and create a new project.
  2. Alternatively, open a Google Sheet, click on Extensions > Apps Script.
  3. Name your project for easy identification later.

Once your script editor is open, you can begin writing your Gmail-sending function using JavaScript syntax.

Basic Gmail Email Sending Function

Here is a basic Apps Script function that sends a plain text email:


function sendSimpleEmail() {
  GmailApp.sendEmail("recipient@example.com", "Test Subject", "This is the email body.");
}

This code does the following:

  • Function Name: sendSimpleEmail — you can rename it to match your purpose
  • Recipient: Replace “recipient@example.com” with your desired email address
  • Subject and Body: Adjust to suit your needs

This method suffices for simple, direct communication, but real-world applications require more sophistication.

Advanced: Sending HTML Emails with Custom Parameters

Let’s create a more flexible function that sends HTML-formatted emails to a list of recipients sourced from Google Sheets.


function sendCustomEmail(recipient, subject, bodyHTML) {
  GmailApp.sendEmail(recipient, subject, '', {
    htmlBody: bodyHTML
  });
}

This function allows you to send an HTML email, enhancing formatting with headings, links, and styles. The '' serves as a placeholder plain-text body, which is still required by the Gmail API even if unused.

Example Use Case: Emailing Data from Google Sheets

Suppose you have a Google Sheet containing names and email addresses of users who need to receive personalized reports. Here’s how you might automate that:


function sendEmailsFromSheet() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Contacts");
  var data = sheet.getRange(2, 1, sheet.getLastRow() - 1, 2).getValues();

  data.forEach(function(row) {
    var name = row[0];
    var email = row[1];
    var subject = "Monthly Report";
    var body = "<p>Dear " + name + ",</p>" +
               "<p>Here is your monthly performance report.</p>" +
               "<p>Best regards,<br>Your Company</p>";
    sendCustomEmail(email, subject, body);
  });
}

This script:

  • Accesses the “Contacts” sheet
  • Grabs data starting from the second row (assuming row 1 is a header)
  • Iterates through each row to personalize emails using the name and email address

The sendCustomEmail helper function is reused, demonstrating modular coding practices.

Using Triggers for Scheduled Emails

Apps Script supports Time-driven Triggers, which enable automated, scheduled execution of your functions. This is invaluable for sending recurring notifications, daily summaries, or monthly reports without manual initiation.

To set a time-based trigger:

  1. In the script editor, click on the clock icon labeled Triggers
  2. Click + Add Trigger
  3. Select your function, e.g., sendEmailsFromSheet
  4. Choose event type: Time-driven
  5. Set the frequency (e.g., daily, weekly, hourly)

This approach guarantees consistent, timely communication without requiring user intervention.

Limitations and Safety Guidelines

Before deploying your email-sending script in a production environment, it’s critical to understand Google’s quotas and best practices.

Gmail Sending Limits:

  • For consumer Gmail accounts: 100 recipients/day
  • For Google Workspace accounts: 1,500 recipients/day (varies by plan)

Exceeding these limits may result in account suspension. To mitigate risks:

  • Test with small batches first.
  • Log email delivery status using Logger.log().
  • Use batching with time-based triggers to stagger sending over multiple days.

Additionally, always ensure your scripts comply with email validation and consent norms, especially under GDPR or similar regulations.

Debugging and Monitoring

Effective debugging is key to maintaining reliable scripts. Apps Script offers integrated debugging tools:

  • Logger: Use Logger.log("message") to inspect variable values.
  • Execution Transcript: View step-by-step logs of your script’s execution.
  • Try-Catch Blocks: Handle errors gracefully with JavaScript’s error handling.

try {
  sendCustomEmail(email, subject, body);
} catch (e) {
  Logger.log("Failed to send email to " + email + ": " + e.message);
}

Logging error messages not only helps identify bugs but also improves visibility for ongoing maintenance.

Conclusion

Using Google Apps Script to automate Gmail emails is a powerful capability that can substantially enhance your workflow. Whether you’re managing a small team or overseeing a large operation, the ability to send customized, automated emails based on real-time data from Google Sheets or other sources is invaluable.

By understanding the core email-sending functions, leveraging advanced formatting, employing triggers for automation, and adhering to Google’s best practice guidelines, you can build a scalable system that truly transforms repetitive tasks into seamless background operations.

As with any automation, always test thoroughly and respect user privacy. With thoughtful implementation, Google Apps Script can become a cornerstone of your productivity toolkit.

You May Also Like