Search code examples
htmlemailgoogle-apps-scriptmobilegmail

Table width in HTML email formatted in AppScript


I have a Google AppScript that produce an HTML code that is used to format email. I would have as output a table with columns with the same width, on PC and mobile phone the table is displayed in different way.

other code ..

body += "<table border=2><tbody><tr>";
  //Inserisco l'header del messaggio
  if (report_headline[0].length > 0) body += CreateHTMLTableRow(report_headline, is_header = true);
  //costruisco la tabella con i dati del report dei messaggi
  if (report_attachement[0].length > 0) body += CreateHTMLTableRow(report_attachement, is_header = false);
  //costruisco la tabella con i dati del report dei pagamenti  
  if (report_payments[0].length > 0) body += CreateHTMLTableRow(report_payments, is_header = false);
  // Close the table tag
  body += "</tbody></table>";

.. other code

//Create an HTML table row from an array
function CreateHTMLTableRow(array,is_header){
  var htmlBody = '';
  var n_row = array.length;
  var n_col = 0;
  var tr_width = 0;
  for (var r = 0; r < n_row; r++) {  
    n_col = array[r].length;
    tr_width = Math.round(100/n_col);
    for (var c = 0; c < n_col; c++) {
      //First row has header <th> tag
      if(is_header){
        if(array[r][c] != ""){
          htmlBody += '<th bgcolor="lightgrey" width="'+tr_width+'"%>'+array[r][c]+"</th>"; 
        }
        else htmlBody += "<th>"+"</th>";        
      }
      //Other rows have the normal <td>
      else {   
        if(array[r][c] != ""){
          htmlBody += '<td width="'+tr_width+'"%>'+array[r][c]+"</td>"; 
        }
        else htmlBody += "<td>"+"</td>";
      }
    }
    htmlBody += "</tr>";
  }  
  return htmlBody;
}  

The gmail client on the mobile device displays the table in the correct way, while on my laptop the second rows are all in the same row.


Solution

  • You define only ONCE the start of a new row:

    body += "<table border=2><tbody><tr>";

    while trying to append within

    for (var r = 0; r < n_row; r++)

    SEVERAL rows.

    The problem can be solved by modifying your code as following:

    body += "<table border=2><tbody>";

    and within function CreateHTMLTableRow(array,is_header):

    for (var r = 0; r < n_row; r++) {  
       // insert a <tr> tag at the start of every new row
        htmlBody +="<tr>";
        n_col = array[r].length;
        ...
        htmlBody += "</tr>";
      }  
      return htmlBody;