Search code examples
javascriptgoogle-apps-scriptscriptinggoogle-ads-apigoogle-ads-script

Google Ads Scripts - Send Logger.log content to email?


I have a script that shows 10 most clicked keywords, their average CPC and conversions. While previewing the script it works fine. But when I send it to my email, only last row of the 10 rows shows. What is wrong here?

function main() {
  var keywords = AdsApp.keywords()
      .orderBy("Clicks DESC")
  //  .orderBy("Impressions DESC")
      .forDateRange("THIS_MONTH")
      .withLimit(10)
      .get();

Logger.log("10 most clicked keywords");
  while (keywords.hasNext()) {
    var keyword = keywords.next();
    content = keyword.getText() + " | Clicks: " + keyword.getStatsFor("THIS_MONTH").getClicks() + " | CPC: " + keyword.getStatsFor("THIS_MONTH").getAverageCpc().toFixed(2) + 
    " | Conversions: " + keyword.getStatsFor("THIS_MONTH").getConversions();
  }
  
MailApp.sendEmail({
            to: '[email protected]',
            subject: "10 most clicked keywords",
            htmlBody: content
});  
  
}


Solution

  • Looks to me like you're over-writing the content variable with every while loop. I think you need to declare content outside the while loop and then add it to your content = string e.g.

    var content = "";      
    while (keywords.hasNext()) {
            var keyword = keywords.next();
            content = content + keyword.getText() + " | Clicks: " + keyword.getStatsFor("THIS_MONTH").getClicks() + " | CPC: " + keyword.getStatsFor("THIS_MONTH").getAverageCpc().toFixed(2) + 
            " | Conversions: " + keyword.getStatsFor("THIS_MONTH").getConversions();
          }
    

    I suspect you'll probably want to add a new line character + "\n" at the end of the concatenations as well.