Gmail – Google Apps Script to automatically send email

gmailgoogle-apps-script

I am trying to create a Google Apps Script that will send an email to our client's general inbox when we receive an email from one of their representatives containing an order. We are required by our contract to provide a receipt of order to a different team on the client side than the team that does the ordering.

I want the script to run every five minutes, and to take all of the new emails that have come in from a specific domain (let's call it @client.com) and forward those emails to a general inbox (let's call it geninbox@client.com).

I have the following script compiled, but as I am very, very new to this and have barely a cursory understanding, I have no idea why it does not work. Any help would be greatly appreciated.

function CLIENTreceipt() {

   var interval = 5; 
   var date = new Date();
   var timeFrom = Math.floor(date.valueOf()/1000) - 60 * interval;
   var threads = GmailApp.search(' from: @client.com is:inbox after:' + timeFrom);
   var msg = "";
   var subject = "";
   var attachment = "";
   for (var i = 0; i < threads.length; i++) {
      t = threads[i];
      c = t.getMessageCount() - 1;
      msg = t.getMessages()[c];
      subject = msg.getSubject();
      attachment = msg.getAttachments();
      msg.forward("geninbox@client.com", {
        subject: "The Following order has Been Received: [" + subject + "]",
        htmlBody: "Thank you!<br><br>"
        +
        "This message is confirm receipt of your order. Your order has been forwarded to our service team.<br><br>",
        attachments: attachment
    });
    t.markRead();
  }
}

Best Answer

It's very likely that the problem is timeFrom is not a string with YYYY/MM/dd format, but instead it's an integer.

To get the string in the required format use Utilities.formatDate()

Reference