将gmail邮件以pdf格式发送到云端硬盘,并添加附件

时间:2019-02-20 06:51:53

标签: google-apps-script scripting google-drive-api gmail

我目前有以下脚本对我们有用了一段时间。它的设计目的是接收带有特定标签的电子邮件,将其转换为pdf,然后将其存储在google驱动器文件夹中。效果很好。现在的问题是,它将电子邮件和附件存储为单独的文件。我们正在尝试将其更改为附件与邮件合并的位置,因此它只是一个大的pdf而不是多个文件。

该过程是手动完成的一段时间,但是负载越来越大。我已经尝试过各种代码,但是运气为零(我不是一个出色的编码器...)。

function saveEmailasPDF() { 
  
  var gmailLabels  = "Bill";  
  var driveFolder  = "Emails";
  
  var threads = GmailApp.search("in:" + gmailLabels, 0, 5);  
  
  if (threads.length > 0) {
    
    // Google Drive folder
    var folders = DriveApp.getFoldersByName(driveFolder);
    var folder = folders.hasNext() ? 
        folders.next() : DriveApp.createFolder(driveFolder);
    
    // Gmail Label
    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 attachments = [];
      
      var subject = threads[t].getFirstMessageSubject();
      
      // Combines the thread into 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 />";
        
        var atts = msg.getAttachments();
        for (var a=0; a<atts.length; a++) {
          attachments.push(atts[a]);
        }
      }
      
      // Save the attachement to drive too and then add a link to the message pdf
      if (attachments.length > 0) {
        var footer = "<strong>Attachments:</strong><ul>";
        for (var z=0; z<attachments.length; z++) {
          var file = folder.createFile(attachments[z]);
          footer += "<li><a href='" + file.getUrl() + "'>" + file.getName() + "</a></li>";
        }
        html += footer + "</ul>";
      }
      
      // Converts the email to a pdf. All the conversation will be in one pdf not seperated
      var tempFile = DriveApp.createFile("temp.html", html, "text/html");
      folder.createFile(tempFile.getAs("application/pdf")).setName(subject + ".pdf");
      tempFile.setTrashed(true);
      
    }
  }
}  

0 个答案:

没有答案