Google Ads Script to Send Budget Alert Emails Automatically

What This Script Does

This script monitors your Google Ads account spending and sends an email alert when you’ve reached 80% of your total monthly budget. It’s designed to help prevent budget overruns by giving you advance notice before you hit your spending limit.

/**

 * Google Ads Script to trigger an alert email when 80% of the overall account budget is spent

 */



// Configuration

var EMAIL_RECIPIENTS = ['xxx@gmail.com']; // Add your email addresses here

var TOTAL_ACCOUNT_BUDGET = 10000; // Total account budget in your currency

var SPENDING_THRESHOLD = 0.80; // 80% threshold



function main() {

  var accountName = AdsApp.currentAccount().getName();

  var accountId = AdsApp.currentAccount().getCustomerId();

  var currencyCode = AdsApp.currentAccount().getCurrencyCode();

  

  // Get account performance report for total cost

  var report = AdsApp.report(

    "SELECT Cost FROM ACCOUNT_PERFORMANCE_REPORT DURING THIS_MONTH"

  );

  

  var rows = report.rows();

  var totalCost = 0;

  

  while (rows.hasNext()) {

    var row = rows.next();

    totalCost += parseFloat(row['Cost']);

  }

  

  var spendingPercentage = (totalCost / TOTAL_ACCOUNT_BUDGET) * 100;

  

  Logger.log("Account: " + accountName);

  Logger.log("Total Cost (This Month): " + formatCurrency(totalCost, currencyCode));

  Logger.log("Spending Percentage: " + spendingPercentage.toFixed(2) + "%");

  

  // Check if spending exceeds the threshold

  if (spendingPercentage >= SPENDING_THRESHOLD * 100) {

    var subject = "Alert: 80% of Account Budget Spent";

    var message = "Hi,\n\nYour Google Ads account has spent 80% or more of its budget.\n" +

                  "Account Name: " + accountName + "\n" +

                  "Account ID: " + accountId + "\n" +

                  "Total Budget: " + formatCurrency(TOTAL_ACCOUNT_BUDGET, currencyCode) + "\n" +

                  "Total Spending: " + formatCurrency(totalCost, currencyCode) + "\n" +

                  "Spending Percentage: " + spendingPercentage.toFixed(2) + "%\n\n" +

                  "Please review your account to ensure it stays within the budget.\n\n" +

                  "This is an automated message from Google Ads.";

    

    sendEmail(EMAIL_RECIPIENTS, subject, message);

  }

}



function formatCurrency(amount, currencyCode) {

  return amount.toLocaleString('en-US', {

    style: 'currency',

    currency: currencyCode

  });

}



function sendEmail(recipientEmails, subject, message) {

  for (var i = 0; i < recipientEmails.length; i++) {

    var recipientEmail = recipientEmails[i];

    

    Logger.log("Sending email to: " + recipientEmail);

    

    MailApp.sendEmail({

      to: recipientEmail,

      subject: subject,

      body: message

    });

  }

}

SCRIPT OUTPUT

Subject: Alert: 80% of Account Budget Spent

Hi,

Your Google Ads account has spent 80% or more of its budget.
Account Name: ABC Marketing
Account ID: 123-456-XXXX
Total Budget: $10,000.00
Total Spending: $8,340.52
Spending Percentage: 83.41%

Please review your account to ensure it stays within the budget.

This is an automated message from Google Ads.

Key Components Breakdown

  1. Configuration Variables:
    • EMAIL_RECIPIENTS: An array containing email addresses that will receive the alert (currently set to ‘ihrk@novonordisk.com‘)
    • TOTAL_ACCOUNT_BUDGET: The maximum amount you plan to spend in your account (set to 10,000 in your account currency)
    • SPENDING_THRESHOLD: The percentage threshold that triggers the alert (set to 0.80, or 80%)
  2. Account Information Collection:
    • Retrieves basic account details like name, ID, and currency code
    • These details are included in the alert email for clear identification
  3. Spending Calculation:
    • Runs a report query to get the total cost for the current month
    • Calculates the percentage of budget spent by dividing current spending by the total budget
    • Formats this information for logging and email purposes
  4. Alert Condition:
    • Checks if spending percentage has exceeded the 80% threshold
    • If threshold is exceeded, prepares an email alert with detailed information
  5. Email Functionality:
    • formatCurrency(): Helper function that formats monetary amounts according to your account’s currency
    • sendEmail(): Function that sends the alert message to all email addresses in the recipients list
    • Uses Google’s MailApp service to deliver the emails

Alert Email Content

The email alert includes:

  • Account name and ID
  • Total budget amount
  • Current spending amount
  • Spending percentage
  • A reminder to review the account to prevent budget overruns

Why This Is Useful

This script provides several benefits:

  1. Budget Control: Helps prevent unexpected overspending by providing early warnings
  2. Proactive Management: Gives you time to make adjustments before hitting your budget limit
  3. Automated Monitoring: Eliminates the need to manually check spending levels daily
  4. Clear Accountability: Ensures budget stakeholders are informed of spending status
  5. Simple Configuration: Easy to adjust thresholds and recipient lists based on your needs

The script runs automatically through Google Ads’ scripting feature, providing peace of mind that you’ll be alerted if spending approaches your limit, allowing you to take action before going over budget.

What This Script Does

This script creates a detailed spreadsheet report of all accounts managed under a Google Ads Manager Account (formerly known as MCC – My Client Center). It extracts budget and spending information for each campaign within every account, allowing you to quickly assess spending patterns across your entire portfolio of managed accounts.

Key Components Breakdown

  1. Spreadsheet Setup:
    • Creates a new Google Sheet with the current date in the title
    • Adds headers for account and campaign data columns
    • Formats the report for readability with auto-sized columns
  2. Account Iteration:
    • Uses AdsManagerApp.accounts().get() to fetch all accounts under the manager account
    • Loops through each account using the select() method to switch context
  3. Data Collection Per Account:
    • Extracts basic account information:
      • Account ID and name
      • Account-level budget (if available)
    • For each campaign within the account, collects:
      • Campaign name
      • Daily budget
      • Total spend (all-time)
      • Percentage of account budget spent
  4. Budget Analysis:
    • The getAccountBudget() helper function attempts to find the account-level budget
    • Applies validation to ensure only meaningful budget values are reported
    • Calculates spending percentages relative to the account budget
  5. Report Formatting:
    • Adds empty rows between accounts for better visual separation
    • Auto-resizes columns to fit content
    • Formats percentage values with two decimal places
  6. Output:
    • Logs the URL of the completed spreadsheet in the Google Ads script console
    • The example shows a successful output to a Google Sheet with ID “12-4H0Pplfsw652lts6ofqMVBwhXzDvmFjlC0W9H49DI”

Why This Is Useful?

This script is particularly valuable for agencies and marketing teams managing multiple Google Ads accounts because it:

  1. Provides Portfolio-Wide Visibility: Consolidates data from all managed accounts into one view, saving time from having to check each account individually
  2. Budget Management: Shows both the absolute spend amounts and relative percentages of budgets used across all campaigns and accounts
  3. Identifies Outliers: Makes it easy to spot accounts or campaigns with unusual spending patterns
  4. Facilitates Client Reporting: Creates a ready-to-share document showing how budgets are being utilized
  5. Improves Resource Allocation: Helps account managers prioritize which accounts need attention based on budget utilization

The script handles cases where account budgets might not be set, gracefully displaying “No account budget” rather than errors, and includes all campaigns regardless of their status to give a complete picture of the account structure.

Steps to Implement Google Ads Script

To implement Google Ads scripts effectively, I’ll walk you through the process step by step:

  1. Access Google Ads Scripts
    • Log into your Google Ads account
    • Click on “Tools & Settings” in the top navigation
    • Select “Scripts” under the “Bulk Actions” section
  2. Create a New Script
    • Click the blue “+” button
    • Give your script a descriptive name that reflects its purpose
  3. Write or Paste Your Script
    • Use the built-in editor to write JavaScript code
    • Google Ads scripts use a specialized JavaScript API specific to Google Ads
  4. Test Your Script
    • Click “Preview” to test your script without making changes
    • Review logs and check for errors in the execution panel
  5. Authorize API Access
    • Grant appropriate permissions when prompted
    • This allows the script to interact with your account data
  6. Schedule Your Script (Optional)
    • Set frequency (hourly, daily, weekly, monthly)
    • Choose specific times for execution
  7. Save and Run Your Script
    • Click “Save” to store your script
    • Click “Run” to execute it immediately if needed

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top