2

I am trying to automatically save the receipts (from Amazon) I receive in GMail to Dropbox. So I have written a script that:

  1. automatically select emails with a certain label
  2. converts the body of the email to html
  3. converts the html to pdf
  4. email the pdf of the body and attachment to IFTTT (which automatically saves the attachments to dropbox)
  5. deletes the temporary files
  6. removes the label

The script works and generates the bodydochtml, but the PDF conversion and email don't work. I am staring at this script for hours. Where is the error in my script?

Thank you!

Function send_Gmail_as_PDF(){

  var gLabel  = "#Receipt";
  var thread = GmailApp.search("label:" + gLabel);
  for (var x=0; x<thread.length; x++) {    
     var messages = thread[x].getMessages();  

     for (var y=0; y<messages.length; y++) {  
       var attach  = messages[y].getAttachments();
       var body    = messages[y].getBody(); 

       // Create an HTML File from the Message Body
       var bodydochtml = DocsList.createFile('body.html', body, "text/html")
       var bodyId=bodydochtml.getId()

       // Convert the HTML to PDF
       var bodydocpdf = bodydochtml.getAs('application/pdf').getBytes();

       // Does the Gmail Message have any attachments?
       if(attach.length>0){

       var file=DocsList.createFile(attach[0]);
       var pdf=file.getAs('application/pdf').getBytes();

       var attach_to_send = {fileName: 'pdftest.pdf',
            content:pdf, mimeType:'application/pdf'};
       var body_to_send = {fileName: 'body.pdf',
           content:bodydocpdf, mimeType:'application/pdf'};

       // Send the PDF to any email address
       MailApp.sendEmail('[email protected]', 
                         'transfer email as pdf : body & attachment', 
                         'see attachment', {attachments:[attach_to_send,body_to_send]});

     // Trash the temporary PDF and HTML files
     file.setTrashed(true);
     DocsList.getFileById(bodyId).setTrashed(true)
     }
   }
}
   // Message Processed; Remove the Google Drive Label
 GmailApp.getUserLabelByName(gLabel)
         .removeFromThread(thread[x]);
}
4
  • Are you getting a specific error message? If so, please include it. Jun 5, 2013 at 17:48
  • I do get "Cannot find method (class)(class)removeFromThread((class)). (line 46, file "Code")", but nothing about failure to convert to PDF or sending the email. Jun 5, 2013 at 19:26
  • @Sergeinsas - Sure, you can create an html file of the body this way. That's not the problem - it's about scoping of variables.
    – Mogsdad
    Jun 5, 2013 at 20:59
  • Keep in mind, you don't actually need to create a temporary file in Google Drive, and then delete it. Google Apps Script has objects called "Blobs" which are essentially disembodied files which can be used for the same purpose. So replace DocsList.createFile() with Utilities.newBlob() and it saves you from having to do all the cleanup later. Jan 16, 2015 at 23:19

3 Answers 3

3

The error on line 46 is coming up when thread[x] is null. Since you've got that statement outside of the loop that deals with thread[x], you ALWAYS have null. Move the statement into the loop, and this problem is avoided.

Inside your message loop, you check whether the message has any attachments, if(attach.length>0){ and only continue with the message if it DOES. Wouldn't you want to continue to send an email with only the pdf body? If so, we need to do something about the fixed array in {attachments:[attach_to_send,body_to_send]}. Better would be to build an array of attachments as we go, starting with the body_to_send. Add:

      var attachmentList = [];
      attachmentList.push(body_to_send);

Better yet, what if the message has multiple attachments - you'd want them all. To do that, put the attachment handling inside a loop, instead of an if, and make sure to move the temp file tidy-up along with it. (That should have been inside the if anyway, because if there was no attachment, the setTrashed() call would crash.)

      // Process all attachments
      for (var att = 0; att < attach.length; att++) {    
        ...
        attachmentList.push(attach_to_send);

        // Trash the temporary file
        file.setTrashed(true);
      }

Here's your code, with these changes - it works nicely:

function send_Gmail_as_PDF() {

  var gLabel = "#Receipt";
  var thread = GmailApp.search("label:" + gLabel);
  for (var x = 0; x < thread.length; x++) {
    var messages = thread[x].getMessages();

    for (var y = 0; y < messages.length; y++) {
      var attach = messages[y].getAttachments();
      var body = messages[y].getBody();

      // Create an HTML File from the Message Body
      var bodydochtml = DocsList.createFile('body.html', body, "text/html")
      var bodyId = bodydochtml.getId()

      // Convert the HTML to PDF
      var bodydocpdf = bodydochtml.getAs('application/pdf').getBytes();

      var body_to_send = {
        fileName: 'body.pdf',
        content: bodydocpdf,
        mimeType: 'application/pdf'
      };

      var attachmentList = [];
      attachmentList.push(body_to_send);

      // Trash the temporary file
      bodydochtml.setTrashed(true);

      // Process all attachments
      for (var att = 0; att < attach.length; att++) {

        var file = DocsList.createFile(attach[att]);
        var pdf = file.getAs('application/pdf').getBytes();

        var attach_to_send = {
          fileName: 'pdftest.pdf',
          content: pdf,
          mimeType: 'application/pdf'
        };
        attachmentList.push(attach_to_send);

        // Trash the temporary file
        file.setTrashed(true);
      }
    }

    // Send the PDF to any email address
    MailApp.sendEmail('[email protected]',
      'transfer email as pdf : body & attachment',
      'see attachment', {
        attachments: attachmentList
      });

    // Message Processed; Remove the Google Drive Label
    GmailApp.getUserLabelByName(gLabel)
      .removeFromThread(thread[x]);
  }
}

Code was put through a prettifier.

0
1

According to Google developers page DocsList has been deprecated.
The code in the answers above should use DriveApp instead.

 function send_Gmail_as_PDF() {

  var gLabel = "#Receipt";
  var thread = GmailApp.search("label:" + gLabel);
  for (var x = 0; x < thread.length; x++) {
    var messages = thread[x].getMessages();

    for (var y = 0; y < messages.length; y++) {
      var attach = messages[y].getAttachments();
      var body = messages[y].getBody();

      // Create an HTML File from the Message Body
      var bodydochtml = DriveApp.createFile('body.html', body, "text/html")
      var bodyId = bodydochtml.getId()

      // Convert the HTML to PDF
      var bodydocpdf = bodydochtml.getAs('application/pdf').getBytes();

      var body_to_send = {
        fileName: 'body.pdf',
        content: bodydocpdf,
        mimeType: 'application/pdf'
      };

      var attachmentList = [];
      attachmentList.push(body_to_send);

      // Trash the temporary file
      bodydochtml.setTrashed(true);

      // Process all attachments
      for (var att = 0; att < attach.length; att++) {

        var file = DriveApp.createFile(attach[att]);
        var pdf = file.getAs('application/pdf').getBytes();

        var attach_to_send = {
          fileName: 'pdftest.pdf',
          content: pdf,
          mimeType: 'application/pdf'
        };
        attachmentList.push(attach_to_send);

        // Trash the temporary file
        file.setTrashed(true);
      }
    }

    // Send the PDF to any email address
    MailApp.sendEmail('[email protected]',
      'transfer email as pdf : body & attachment',
      'see attachment', {
        attachments: attachmentList
      });

    // Message Processed; Remove the Google Drive Label
    GmailApp.getUserLabelByName(gLabel)
      .removeFromThread(thread[x]);
  }
}
1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Feb 21, 2022 at 14:22
-1

this code I wrote a while ago does the job if the attachement is in a format that can be converted to pdf. It gets the message in the last thread and sends both body and attachment only if an attachment is present. This is a test script.

function getAttachAndBody(){
  var firstThread = GmailApp.getInboxThreads(0,1)[0];
  var message = firstThread.getMessages()[0];
  var attach = message.getAttachments();
  var body = message.getBody();//is a string
  var bodydochtml = DocsList.createFile('body.html', body, "text/html")
  var bodyId=bodydochtml.getId()
  var bodydocpdf = bodydochtml.getAs('application/pdf').getBytes();
  if(attach.length>0){
    var file=DocsList.createFile(attach[0])
    var pdf=file.getAs('application/pdf').getBytes();
    var attach_to_send = {fileName: 'pdftest.pdf',content:pdf, mimeType:'application/pdf'};
    var body_to_send = {fileName: 'body.pdf',content:bodydocpdf, mimeType:'application/pdf'};
//    MailApp.sendEmail('[email protected]', 'transfer email as pdf : body ', 'see attachment', {attachments:[body_to_send]});
    MailApp.sendEmail('[email protected]', 'transfer email as pdf : body & attachment', 'see attachment', {attachments:[attach_to_send,body_to_send]});
    file.setTrashed(true);
    DocsList.getFileById(bodyId).setTrashed(true)
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.