1
votes

Relatively new google scripts.

What I am trying to do is

  1. Select all the specified emails in a label in Gmail
  2. Save each email as a separate pdf (using subject) and save in a the specified folder in google drive
  3. Generate a link to that pdf
  4. Save in spreadsheet the

    a)Date

    b)Subject

    c)Plain Body Txt

    d)Html Body Txt

    e)Link to each pdf file

The following code is generating the points a to d

    function myFunction() {


  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Sheet1");

  var label = GmailApp.getUserLabelByName("MY LABEL");
  var threads = label.getThreads();

  for (var i=0; i<threads.length; i++)
  {
    var messages = threads[i].getMessages();

    for (var j=0; j<messages.length; j++)
    {
      var msghtml = messages[j].getBody();
      var msgplain = messages[j].getPlainBody();
      var sub = messages[j].getSubject();
      var dat = messages[j].getDate();

      ss.appendRow([dat,sub,msgplain,msghtml])
    }
      threads[i].removeLabel(label);
  }
}

Need to add the functionality to save each file as separate pdf (using) and add link to this sheet

There are already some threads where people are generating the pdfs from the gmail threads

Automatically convert emails with a Gmail label to PDF and send it to an email address

Convert PDFs to Google docs and get extracted text along with link to original PDF file into a spreadsheet

But don't know how to incorporate it into the existing code to make it work.

PS:If it can be made into something that adds any new emails to the sheet that would be awesome

1
Are you interested only in the body of the email or also the attachment?ziganotschka

1 Answers

0
votes

You can modify your script by adding / modifying the following lines:

      var textFile=DriveApp.createFile('email-'+sub+'-'+dat, msghtml,"text/html"); //modify the file name as desired
      var blob = textFile.getAs(MimeType.PDF);
      var pdf= DriveApp.createFile(blob);
      var pdfLink=pdf.getUrl();
      ss.appendRow([dat,sub,msgplain,msghtml,pdfLink])

Basically, in order to export your email to PDF

To obtain the link, use getUrl().