0
votes

I'm a complete noob.

I'd like to forward labelled emails on the 1st of every month to another email address. Using Gmail's filters, the label "forwardthis" get applied to my invoices and statements I received during the month. On the 1st of every month, I'd like Google scrips to forward all new emails with the "forwardthis" label to another email address, including attachments.

The script I found doesn't work as I hoped. Not sure what the interval options below are for, but I need to run my script only once a month, on the 1st.

function autoForward() {
    var label = 'forwardthis';
    var recipient = '[email protected]';
    var interval = 5;          //  if the script runs every 5 minutes; change otherwise
    var date = new Date();
    var timeFrom = Math.floor(date.valueOf()/1000) - 60 * interval;
    var threads = GmailApp.search('label:' + label + ' after:' + timeFrom);
    for (var i = 0; i < threads.length; i++) {
        threads[i].getMessages()[0].forward(recipient);  // only the 1st message
    }
}

Hope my question is clear. I'll greatly appreciate some guidance, thanks.

1

1 Answers

0
votes

Sends labeled emails created after the last time the script was run

Evidently the script was meant to run every 5 minutes so rather that keeping tracked of emailed labels already sent the script just takes the labels created after the current time minus the interval or in other words the labeled emails received since the last time the script was run.

Since you want to run the script on the first of every month you will have to figure how to get the time for the 1st of last month and put that value into the timefrom variable.

function autoForward() {
    var label = 'forwardthis';
    var recipient = '[email protected]';
    var interval = 5;          //  if the script runs every 5 minutes; change otherwise
    var date = new Date();
    var timeFrom = Math.floor(date.valueOf()/1000) - 60 * interval;//This subtracts five minutes from the current time
    var threads = GmailApp.search('label:' + label + ' after:' + timeFrom);//Emails with the correct label and created since 5 minutes ago are sent
    for (var i = 0; i < threads.length; i++) {
        threads[i].getMessages()[0].forward(recipient);  // only the 1st message
    }
}

Noob or not, you can figure this out.
Most of what you need is right here.
Or possibly here.
You can use triggers to run your script once a month. You can read about triggers here.
I hope that helps.