Mee
Mee

Reputation: 145

Google sheets sending email -added var now throwing error

I have created this script and it is for all intent and purposes working, it is sending my emails etc. but for some reason the error message comes up

"Exception: Failed to send email: no recipient (line 17, file "Code")"

Line 17 is the subject var so not sure why it is expecting it to be an email. Anyone got an idea why it is?

Here is my code...

/**
 * Sends emails with data from the current spreadsheet.
 */
function sendEmails() {

    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("email sender")

        var startRow = 2; // First row of data to process

    var numRows = 1000; // Number of rows to process

    // Fetch the range of cells A2:C3

    var dataRange = sheet.getRange("A2:C");

    // Fetch values for each row in the Range.

    var data = dataRange.getValues();

    for (var i in data) {

        var row = data[i];
        var emailAddress = row[0]; // First column
        var message = row[1]; // Second column
        var subject = 'Sending emails from a Spreadsheet';
        MailApp.sendEmail(emailAddress, subject, message, {
            htmlBody: message
        });
    }
}

Thanks a lot

Upvotes: 0

Views: 64

Answers (1)

ziganotschka
ziganotschka

Reputation: 26836

This error means that some cell in column A are empty and thus do not contain valid E-mail addresses

  • What about if instead sheet.getRange("A2:C"); you define sheet.getRange(1,2,sheet.getlastRow,3); using numerical row and column references? This will make sure that you don't run your code on empty rows
  • Also, you can implement a statement checking either the recipient field is empty before sending an email:
if(emailAddress != "" && emailAddress != " "){
  MailApp.sendEmail(emailAddress, subject, message, {
    htmlBody: message
  });
}

Upvotes: 1

Related Questions