自动将带有Gmail标签的电子邮件转换为PDF并将其发送到电子邮件地址

时间:2013-06-05 17:24:13

标签: google-apps-script gmail

我正在尝试将我在GMail中收到的收据(从亚马逊)自动保存到Dropbox。所以我写了一个脚本:

  1. 自动选择具有特定标签的电子邮件
  2. 将电子邮件正文转换为html
  3. 将html转换为pdf
  4. 通过电子邮件发送正文的附件和附件到IFTTT(自动将附件保存到保管箱)
  5. 删除临时文件
  6. 删除标签
  7. 脚本工作并生成bodydochtml,但PDF转换和电子邮件不起作用。我盯着这个剧本几个小时。我的脚本中的错误在哪里?

    谢谢!

    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('myemail@gmail.com', 
                             '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]);
    }
    

2 个答案:

答案 0 :(得分:3)

thread[x]为空时,第46行的错误即将出现。既然你已经在循环之外处理了线程[x],那么你总是有空。将语句移动到循环中,避免了这个问题。

在消息循环中,您检查消息是否包含任何附件if(attach.length>0){,并且只有消息才会继续。您不想继续发送仅包含pdf正文的电子邮件吗?如果是这样,我们需要对{attachments:[attach_to_send,body_to_send]}中的固定数组做一些事情。更好的方法是从body_to_send开始构建一系列附件。添加:

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

更好的是,如果邮件有多个附件,那么你会想要它们。为此,将附件处理放在循环中,而不是if,并确保将临时文件与其一起整理。 (那应该在if内部,因为如果没有附件,setTrashed()调用会崩溃。)

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

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

这是您的代码,通过这些更改 - 它运作良好:

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('myemail@gmail.com',
      'transfer email as pdf : body & attachment',
      'see attachment', {
        attachments: attachmentList
      });

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

代码通过prettifier

答案 1 :(得分:0)

我刚才写的这段代码如果附件的格式可以转换为pdf,那就完成了这项工作。 它在最后一个线程中获取消息,并仅在存在附件时发送正文和附件。 这是一个测试脚本。

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('xxxxxxx@gmail.com', 'transfer email as pdf : body ', 'see attachment', {attachments:[body_to_send]});
    MailApp.sendEmail('xxxxxxx@gmail.com', 'transfer email as pdf : body & attachment', 'see attachment', {attachments:[attach_to_send,body_to_send]});
    file.setTrashed(true);
    DocsList.getFileById(bodyId).setTrashed(true)
    }
}