Send a pdf attachment on email to Google Chat space


An pdf export is configured from some external system into your Gmail inbox.

You take this pdf export, and forward it on to a Google Chat Space for wider consumption.


You do this for 7 different kinds of reports. It is easy to forget about a specific report or send the wrong report into the wrong Google Chat Space.


Automate the process of forwarding the email attachment from email to Google Chat.

The automation can be achieved using Google Apps script. (See resources here if Google Apps Script is new to you)

Services used:

  1. Gmail
  2. Google Chat
  3. Google Apps Script


  1. schedule pdf export from some system to Gmail address
  2. Save the pdf email attachment to Google Drive
  3. Move the pdf to specified folder
  4. Send link to pdf file in a message on Google Chat

Below is the code which executes these steps using Google Apps Script.

// set global variables for use throughout script

// dates
var my_now = new Date();
var my_month = my_now.getMonth() + 1;
var my_date = my_now.getFullYear() + "-" + my_month + "-" + my_now.getDate();

var pdfFileId = "";

// this is the webhook for the Google chat space to send a message into
// change this line to send a message into another Google chat space
var WebWhooklink = "";

var googleChatMessage = "Hello \n";


function mainDriver() {


function getPDFFromEmail() {
    var threads =" subject:\"Sponsored Products activity trends\"");
    // get latest message in thread
    var message = threads[0].getMessages()[0];
    var sentDate = message.getDate();
    // Loop through all message attachments
    var i;
    for (i = 0; i < message.getAttachments().length; i++) {
      var attachment = message.getAttachments()[i];
      // Is the attachment a PDF file
      // There should only be 1 pdf attached
      // Behaviour of script may be unexpected if multiple pdf's are attached.
      if (attachment.getName().endsWith(".pdf")) {
        // Get the attachment's content.
        //var content = attachment.getContent();
        //var content = attachment.copyBlob

        // Create a new file in Google Drive.
        var my_file = DriveApp.createFile(attachment.copyBlob().setName("Sponsored Products report " + my_date + ".pdf"));

        // get file id
        pdfFileId = my_file.getId();

        // Move the file to the destination folder

function sendPDFGoogleChat() { 
    // sends a message into the "Marquin Test" google chat space

    var message = {
    text: googleChatMessage + "" + pdfFileId + "/view"
    var payload = JSON.stringify(message);
    var options = {
            method: "POST",
            contentType: "application/json",
            payload: payload

    var response =  UrlFetchApp.fetch(WebWhooklink, options ).getContentText();

Send a Comment

Your email address will not be published.