Excelsson
Excelsson

Reputation: 195

Google Sheets Send Range as Email

I'm trying to send an specific range as a Pdf attachment or HTML Table in an email, the cells a2 will have the email and the message should be on the range C7:I25, this is what I have so far, I'm getting the error, no recipient found, can you please help me?

function correoe() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;  
  var numRows = 2;   
  var dataRange = sheet.getRange(startRow, 1, numRows, 5)
  var data = dataRange.getValues();
  for (i in data) {
    var row = data[i];
    var emailAddress = row[0];  
    var message = sheet.getRange ("C7:I25");
    var subject = "Su Cotizacion";
    MailApp.sendEmail(emailAddress, subject, message);
  }
}

Upvotes: 1

Views: 3549

Answers (1)

Max Makhrov
Max Makhrov

Reputation: 18707

You need some function to get html text out of cells.

var data = sheet.getRange ("C7:I25").getValues();
var message = getTable(data);

The function getTable might look like this:

  function getTable(data) {
    var result = ["<table border=1'>"];
    var ll = data[0].length;
    var row = 0;
    for(var i = 0, l = data.length; i < l; i++) {
        row = data[i];
        result.push("<tr>");
        for(var ii = 0; ii < ll; ii++){
            result.push('<td>' + row[ii] + '</td>');
        }
        result.push("</tr>");
    }
    result.push("</table>");
    return result.join('\n');
  }

Test

Dummy data

[["row 1, cell 1", "row 1, cell 2"], 
 ["row 2, cell 1", "row 2, cell 2"]];

Dummy HTML text output

<table border=1'>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table

Usage

Need to use this syntax to send an email:

 MailApp.sendEmail({
     to: emailAddress,
     subject: subject,
     htmlBody: message
 });

Upvotes: 2

Related Questions