Send a pdf attachment on email to Google Chat space

Situation

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.

Complication

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.

Solution

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

Stages:

  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 = "https://chat.googleapis.com/v1/spaces/AAAAnX1yKek/messages?key=AIzaSyDdI0hCZtE6vySjMm-WEfRq3CPzqKqqsHI&token=hUnvSmKAiZySJD8QR6z029Q7E_ktWgPtaaFkEwz8gLE";

var googleChatMessage = "Hello \n";

var DESTINATION_FOLDER_ID = "1V6Na3IgQEV0u1Y7Br26PmAMXTJCMRCJ5"

function mainDriver() {
  getPDFFromEmail();

  sendPDFGoogleChat();
}

function getPDFFromEmail() {
    var threads = GmailApp.search("from:looker-studio-noreply@google.com subject:\"Sponsored Products activity trends\"");
  
    // get latest message in thread
    Logger.log(threads.length)
    var message = threads[0].getMessages()[0];
    var sentDate = message.getDate();
    //Logger.log(message);
    //Logger.log(sentDate)
  
    // 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
        my_file.moveTo(DriveApp.getFolderById(DESTINATION_FOLDER_ID));
  
    }
    }
}

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

    var message = {
    text: googleChatMessage + " https://drive.google.com/file/d/" + 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.