1

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 Answers1

0

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().

ziganotschka
  • 25,866
  • 2
  • 16
  • 33
  • 1
    I thought that in OP's goal, the email might not be required to create as the text file. So how about modifying `var textFile=DriveApp.createFile('email-'+sub+'-'+dat, msghtml,"text/html"); var blob = textFile.getAs(MimeType.PDF);` to `var blob = Utilities.newBlob(msghtml, MimeType.HTML, 'email-'+sub+'-'+dat).getAs(MimeType.PDF);`? By this, the HTML can be converted to the PDF format without creating the text file. But if this was not the direction OP wants, I apologize. – Tanaike Dec 12 '19 at 23:59
  • 1
    Thank you for your suggestion @Tanaike, this is a good idea because it saves one step. – ziganotschka Dec 13 '19 at 08:56