Monday, 11 March 2019

Email scheduler for Gmail - send email

Overview blog post.

The following Google Apps Script code sends the email when the trigger runs and writes the date/time back to the spreadsheet as a record.
Screenshot of text to confirm message delivery
Confirmation of message delivery
After gathering the spreadsheet data the script gets the current date/time and begins to loop through each row looking for messages to be sent. Only messages with a Scheduled status and valid date/time will be dealt with. An important step of the script is to check the scheduled date/time is not in the future - as these messages will have their own trigger to run at a later date - we only want messages up until now that have not been sent.
Using the 'GmailApp' we can 'getMessageById' since we have it stored in the spreadsheet (this is how we access the draft message) and subsequently extract the relevant parts:
var body = message.getBody();
    var options = {
            cc: message.getCc(),
            bcc: message.getBcc(),
            htmlBody: body,
            attachments: message.getAttachments()
    }
We then use a Try/Catch to 'sendEmail' (so the script does not just crash if it encounters an error), remove it from drafts ('moveToTrash') and finally 'setValue' of status Delivered along with the date/time this function began.

Finally we delete the corresponding trigger by running the deleteTrigger function which will be described in a later blog post and 'clearContent' of the Schedule ID column.

No comments:

Post a Comment