Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

462
Vistas
Converting emails to PDF if subject equals "xxxxx" and date equals today

I have written a script which has a trigger to run every hour, it searches my emails and extracts the data, turns it to a PDF and locates it in a folder if the subject equals "xxxx", it overwrites data in the folder if it already exists.. I would like to add in a new if function where it will only pick up emails for the current day and not history (to save efficiency of the script and data)

function saveGmailAsPDF2() {

  var gmailLabels  = 'xxxxx';
  var driveFolder  = DriveApp.getFolderById("folder url");
  var threads = GmailApp.search("subject:" + gmailLabels,0,20);

  if (threads.length > 0) {

  /* Google Drive folder where the Files would be saved */
  var folders = DriveApp.getFoldersByName(driveFolder);
  var folder = folders.hasNext() ?
  folders.next() : DriveApp.createFolder(driveFolder);

  /* Gmail Label that contains the queue */
  var label = GmailApp.getUserLabelByName(gmailLabels) ?
  GmailApp.getUserLabelByName(gmailLabels) : GmailApp.createLabel(driveFolder);

  for (var t=0; t<threads.length; t++) {

  threads[t].removeLabel(label);
  var msgs = threads[t].getMessages();

  var html = "";

  var subject = threads[t].getFirstMessageSubject();

  var previousdoc = driveFolder.getFilesByName(subject + ".pdf"); //gets name of csv, if exists in drive then move to trash before creating new file
  if (previousdoc.hasNext()) {
  previousdoc.next().setTrashed(true);}

  /* Append all the threads in a message in an HTML document */
  for (var m=0; m<msgs.length; m++) {

  var msg = msgs[m];

  html += "From: " + msg.getFrom() + "<br />";
  html += "To: " + msg.getTo() + "<br />";
  html += "Date: " + msg.getDate() + "<br />";
  html += "Subject: " + msg.getSubject() + "<br />";
  html += "<hr />";
  html += msg.getBody().replace(/<img[^>]*>/g,"");
  html += "<hr />";}

  /* Convert the Email Thread into a PDF File */

  var tempFile = DriveApp.createFile("temp.html", html, "text/html");
  folder.createFile(tempFile.getAs("application/pdf")).setName(subject + ".pdf");
  tempFile.setTrashed(true);}}}

  
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Explanation:

  • There is a function getLastMessageDate() that gives the date of a thread's most recent message. You can compare that against the date of today and if they match execute the rest of the code.

  • Since you use a for loop: for (var t=0; t<threads.length; t++) I think the condition if (threads.length > 0) is redundant because for loop won't run anyway if threads.length equals 0.

  • Because of the latter, I transferred the folder creation part of your code into the loop itself and execute it only when the last day of the thread is equal to today. But I leave this part for you to decide.

I can't test your code but this should work:

function saveGmailAsPDF2() {

  var gmailLabels  = 'xxxxx';
  var driveFolder  = DriveApp.getFolderById("folder url");
  var threads = GmailApp.search("subject:" + gmailLabels,0,20);

  // new code
  const today = new Date();
  const ss = SpreadsheetApp.getActive();
  const timezone = ss.getSpreadsheetTimeZone();
  const today_dt = Utilities.formatDate(today, timezone, 'yyyy-MM-dd');
  ///////////
 

  for (var t=0; t<threads.length; t++) {

  // new code
  var lastMessageDate = threads[t].getLastMessageDate();
  var thread_dt = Utilities.formatDate(lastMessageDate, timezone, 'yyyy-MM-dd');
  if(today_dt==thread_dt){
   ///////////
   
   /* Google Drive folder where the Files would be saved */
  var folders = DriveApp.getFoldersByName(driveFolder);
  var folder = folders.hasNext() ?
  folders.next() : DriveApp.createFolder(driveFolder);

  /* Gmail Label that contains the queue */
  var label = GmailApp.getUserLabelByName(gmailLabels) ?
  GmailApp.getUserLabelByName(gmailLabels) : GmailApp.createLabel(driveFolder);


  threads[t].removeLabel(label);
  var msgs = threads[t].getMessages();

  var html = "";

  var subject = threads[t].getFirstMessageSubject();

  var previousdoc = driveFolder.getFilesByName(subject + ".pdf"); //gets name of csv, if exists in drive then move to trash before creating new file
  if (previousdoc.hasNext()) {
  previousdoc.next().setTrashed(true);}

  /* Append all the threads in a message in an HTML document */
  for (var m=0; m<msgs.length; m++) {

  var msg = msgs[m];

  html += "From: " + msg.getFrom() + "<br />";
  html += "To: " + msg.getTo() + "<br />";
  html += "Date: " + msg.getDate() + "<br />";
  html += "Subject: " + msg.getSubject() + "<br />";
  html += "<hr />";
  html += msg.getBody().replace(/<img[^>]*>/g,"");
  html += "<hr />";}

  /* Convert the Email Thread into a PDF File */

  var tempFile = DriveApp.createFile("temp.html", html, "text/html");
  folder.createFile(tempFile.getAs("application/pdf")).setName(subject + ".pdf");
  tempFile.setTrashed(true);}}}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda