Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Last active November 22, 2022 07:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanaikech/12a61cb7e4516acc95ecf15287b3f0f3 to your computer and use it in GitHub Desktop.
Save tanaikech/12a61cb7e4516acc95ecf15287b3f0f3 to your computer and use it in GitHub Desktop.
Converting Gmail Message to Image using Google Apps Script

Converting Gmail Message to Image using Google Apps Script

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment