使用 Google Apps 脚本,如何检查电子邮件是否附加了 pdf,然后将其转发到另一个电子邮件地址?

Using Google Apps script, how to check if an email has a pdf attached to it, then forward it to another email address?

我设法创建了一个函数,可以将电子邮件转换为 pdf,然后将其转发到另一个电子邮件地址(我使用了 Mike Greiling 制作的这个很棒的库:https://github.com/pixelcog/gmail-to-pdf)。

但现在我想创建另一个功能来检查电子邮件是否已经有附件,然后立即转发它。

这是我的工作函数:

function saveExpenses() {

    GmailUtils.processStarred( 'label: test', 5, function(message) {

    // create a pdf of the message
    var pdf = GmailUtils.messageToPdf(message);

    // prefix the pdf filename with a date string
    pdf.setName(GmailUtils.formatDate(message, 'yyyy/MM/dd - ') + pdf.getName());   

     // send confirmation email to the original sender 
     var confirmationEmail = message.getFrom();

     // Get the name of the document to use as an email subject line.
     var subject =  pdf.getName();

     var body = "This is a confirmation that this receipt has been sent";

     // Send a confirmation email to the sender
     GmailApp.sendEmail(confirmationEmail, subject, body,  {attachments: [pdf]});

    return true;

  });
 }
} 

好的,我找到了解决方案,其实很简单。 我想我想得还不够,所以基本上我只是用函数 getAttachments 从消息中获取所有附件,其中 returns 一个 attachments 的数组,然后我只检查长度是否数组的大于0(表示邮件中有附件) 如果结果为0,则表示没有附件。

这是我所做的:

var attachment = message.getAttachments();

    if (attachment.length > 0 ) {
          // I add the code to deal with the attachment

    } else if  (attachment.length == 0 ) {
          // I add the code that I posted in the question above
    }