Converting Gmail Message to Image using Google Apps Script

Gists

This is a workaround for converting a Gmail message to a PNG image using Google Apps Script.

Sample script

Please set the message ID of Gmail.

function myFunction() {
  var id = "###"; // Please set your message ID of Gmail.

  var message = GmailApp.getMessageById(id);
  var date = Utilities.formatDate(
    message.getDate(),
    Session.getScriptTimeZone(),
    "yyyy-MM-dd HH:mm:ss"
  );
  var from = message.getFrom();
  var to = message.getTo();
  var subject = message.getSubject();
  var htmlBody = message.getBody();
  var imageBlob = Charts.newTableChart()
    .setDataTable(
      Charts.newDataTable()
        .addColumn(Charts.ColumnType.STRING, "")
        .addRow([`<p style="font-size: 120%">Date: ${date}</p>`])
        .addRow([`<p style="font-size: 120%">From: ${from}</p>`])
        .addRow([`<p style="font-size: 120%">To: ${to}</p>`])
        .addRow([`<p style="font-size: 120%">Subject: ${subject}</p>`])
        .addRow([htmlBody])
        .build()
    )
    .setOption("allowHtml", true)
    .setDimensions(512, 512)
    .build()
    .getBlob();

  DriveApp.createFile(imageBlob.setName("sample.png"));
}
  • In this sample script, the HTML body is used.

  • When this script is run, a Gmail message is retrieved and it is converted to a PNG image. In this sample script, the PNG file is created in the root folder.

  • In this sample, the image size is 512 x 512 by setDimensions(512, 512). If your HTML body is large, please modify this size for your actual situation.

Reference

 Share!