Your Uncommonly Amazing WordPress Tech Partner
Membership plugins

How to set up a Gmail Auto Reply for Office Hours

gmail-auto-reply-office-hours

[et_pb_section fb_built=”1″ _builder_version=”3.22.3″ custom_margin=”-5px|||||” custom_padding=”3px||4px|||”][et_pb_row _builder_version=”4.0.4″ custom_padding=”4px|||||”][et_pb_column type=”4_4″ _builder_version=”4.0.4″][et_pb_text _builder_version=”4.0.4″ custom_margin=”||-1px|||” custom_padding=”||0px|||”]

Introduction

Overview

If you plan to be away from your Gmail account—say, a vacation or a place without access to the internet—you can set up a vacation responder in Gmail to automatically notify people that you won't be able to get back to them right away.

When the autoresponder is active, whenever somebody sends you an email, they'll receive an email response containing what you've written in your vacation auto reply.

That's all Gmail 101…

But what if you want to reply to your customer even while you are not on vacation?

(Like, for example, when your office is closed).

Well, there is a script that helps you to do that!

Video Tutorial

_builder_version=”3.29.3″ custom_margin=”7px|auto||auto||” custom_padding=”7px|||||”][et_pb_column type=”4_4″ _builder_version=”3.29.3″][et_pb_text _builder_version=”4.0.2″ custom_margin=”||-1px|||” custom_padding=”||0px|||”]

Setting up the Gmail AUTORESPONDER script

The instructions on this article work for Gmail or G Suite email accounts.

1 – Go to https://www.google.com/script/start/ and click on the ‘Start Scripting‘ button.

2 – Click New Script at the top left.
New Script 300x143 - How to set up a Gmail Auto Reply for Office Hours

3 – Rename the project to whatever you want (where you see “Untitled project”) – this will be the app name.

Rename Project 320x200 - How to set up a Gmail Auto Reply for Office Hours

4 –  Replace the code in Code.gs with the code below:

[/et_pb_text][/et_pb_column][/et_pb_row][et_pb_row _builder_version=”3.25″ z_index_tablet=”500″][et_pb_column type=”4_4″ _builder_version=”3.25″ custom_padding=”|||” custom_padding__hover=”|||”][et_pb_blurb title=”gs” use_icon=”on” font_icon=”%%208%%” icon_color=”#3366cc” icon_placement=”left” use_icon_font_size=”on” icon_font_size=”20px” _builder_version=”4.0.4″ header_text_color=”#ffffff” header_font_size=”16″ header_line_height=”1.3em” background_color=”#000000″ width=”100px” custom_margin=”||-42px|-50px” custom_padding=”10px|15px|2px|15px” z_index_tablet=”500″][/et_pb_blurb][et_pb_text module_class=”mfcodes” _builder_version=”3.27.4″ text_font=”Source Code Pro||||||||” text_font_size=”15px” background_color=”#eff0f4″ custom_margin=”|||60px” custom_padding=”3%|3%|3%|3%” z_index_tablet=”500″ border_width_top=”7px” border_color_top=”#3366cc” border_width_top_tablet=”7px” border_width_top_phone=”7px” box_shadow_horizontal_tablet=”0px” box_shadow_vertical_tablet=”0px” box_shadow_blur_tablet=”40px” box_shadow_spread_tablet=”0px”]
function autoReply() {
var interval = 5; // if the script runs every 5 minutes; change otherwise
var wkend = [6,0]; // 1=Mo, 2=Tu, 3=We, 4=Th, 5=Fr, 6=Sa, 0=Su
var wkendMessage = "Hi, Thank you for contacting us. The office is now closed. All emails will be attended to when the office re-opens at 9:00am PST on Monday morning.";
var wkdayMessage = "Hi! Thank you for your email. The office hours are Mondays – Fridays 9-6pm PST. Thank you for your patience!";
var date = new Date(); var day = date.getDay(); var hour = date.getHours(); if (wkend.indexOf(day) > -1 || (day == 5 && hour >= 18)) { var timeFrom = Math.floor(date.valueOf()/1000) - 60 * interval; var threads = GmailApp.search('is:inbox after:' + timeFrom); for (var i = 0; i < threads.length; i++) { threads[i].reply(wkendMessage); } } else if (hour < 9 || hour >= 18) { var timeFrom = Math.floor(date.valueOf()/1000) - 60 * interval; var threads = GmailApp.search('is:inbox after:' + timeFrom); for (var i = 0; i < threads.length; i++) { threads[i].reply(wkdayMessage); } } }
function doGet() {
 return ContentService.createTextOutput(”");
}
[/et_pb_text][/et_pb_column][/et_pb_row][et_pb_row _builder_version=”3.29.3″][et_pb_column type=”4_4″ _builder_version=”3.29.3″][et_pb_text _builder_version=”4.7.7″ custom_margin=”||-1px|||” custom_padding=”||0px|||”]

5 – Customize the message based on your needs.

The current message is a generic one that is set for offices that work from 09:00AM to 18:00PM.

6 –  Customize the days based on your needs.

The current week day message will be sent from Monday to Friday.

7 – When the customization is completed, click Save and Run.

8 – Then click Publish > Deploy as Web App
Web app 300x91 - How to set up a Gmail Auto Reply for Office Hours

9 – Authorize the script with your Gmail Account.

10 – Go back into “My Projects” on the dashboard

11 – Click the 3 dots icon next to the project name

12 – Select Triggers

13 – Click on Add Triggers button will appear at the bottom right

14 – Choose next options:

Choose which function to run – Autoreply
Which runs at deployment – Head
Select Event Source – Time-Driven
Select type of time based trigger – Minutes Times
Select Minute Interval – Every 5 Minutes                
Failure Notification Settings – Notify me dail

15 – Click on save

16 – Test the script and verify it works.

[/et_pb_text][/et_pb_column][/et_pb_row][et_pb_row _builder_version=”3.25″ background_size=”initial” background_position=”top_left” background_repeat=”repeat” custom_margin=”-6px|auto||auto||” custom_padding=”10px||11px|||”][et_pb_column type=”4_4″ _builder_version=”3.25″ custom_padding=”|||” custom_padding__hover=”|||”][et_pb_text _builder_version=”4.0.2″ custom_margin=”||-1px|||” custom_padding=”5px||0px||false|false” z_index_tablet=”500″ text_text_shadow_horizontal_length_tablet=”0px” text_text_shadow_vertical_length_tablet=”0px” text_text_shadow_blur_strength_tablet=”1px” link_text_shadow_horizontal_length_tablet=”0px” link_text_shadow_vertical_length_tablet=”0px” link_text_shadow_blur_strength_tablet=”1px” ul_text_shadow_horizontal_length_tablet=”0px” ul_text_shadow_vertical_length_tablet=”0px” ul_text_shadow_blur_strength_tablet=”1px” ol_text_shadow_horizontal_length_tablet=”0px” ol_text_shadow_vertical_length_tablet=”0px” ol_text_shadow_blur_strength_tablet=”1px” quote_text_shadow_horizontal_length_tablet=”0px” quote_text_shadow_vertical_length_tablet=”0px” quote_text_shadow_blur_strength_tablet=”1px” header_text_shadow_horizontal_length_tablet=”0px” header_text_shadow_vertical_length_tablet=”0px” header_text_shadow_blur_strength_tablet=”1px” header_2_text_shadow_horizontal_length_tablet=”0px” header_2_text_shadow_vertical_length_tablet=”0px” header_2_text_shadow_blur_strength_tablet=”1px” header_3_text_shadow_horizontal_length_tablet=”0px” header_3_text_shadow_vertical_length_tablet=”0px” header_3_text_shadow_blur_strength_tablet=”1px” header_4_text_shadow_horizontal_length_tablet=”0px” header_4_text_shadow_vertical_length_tablet=”0px” header_4_text_shadow_blur_strength_tablet=”1px” header_5_text_shadow_horizontal_length_tablet=”0px” header_5_text_shadow_vertical_length_tablet=”0px” header_5_text_shadow_blur_strength_tablet=”1px” header_6_text_shadow_horizontal_length_tablet=”0px” header_6_text_shadow_vertical_length_tablet=”0px” header_6_text_shadow_blur_strength_tablet=”1px” box_shadow_horizontal_tablet=”0px” box_shadow_vertical_tablet=”0px” box_shadow_blur_tablet=”40px” box_shadow_spread_tablet=”0px”]

Results

Voila! Your after working hours emails will be auto-replied for you!

Using this script will allow you to maintain high levels of customer service!

What do you think of this tutorial?

Article Title: How to set up a Gmail Auto Reply for Office Hours

Short Description: Learn how to set up a Gmail autoresponder that applies to certain parts of the day only.

Author: Ardian Lumi

Publisher - Orgnization: MemberFix

Publisher Logo: mermberfix logo x200 1 - How to set up a Gmail Auto Reply for Office Hours

User Review
0 (0 votes)

 

[/et_pb_text][/et_pb_column][/et_pb_row][et_pb_row column_structure=”1_4,3_4″ make_equal=”on” _builder_version=”3.25″ custom_margin=”||30px|” custom_margin_tablet=”” custom_margin_phone=”” custom_margin_last_edited=”on|phone” custom_padding=”0px|0px|0px|0px” border_width_all=”1px” border_color_all=”#2ecc71″][et_pb_column type=”1_4″ _builder_version=”3.25″ background_color=”#2ecc71″ custom_padding=”|||” custom_padding__hover=”|||”][et_pb_blurb use_icon=”on” font_icon=”%%49%%” icon_color=”#ffffff” _builder_version=”3.0.91″ custom_margin=”30px||5px|” custom_padding=”|||” custom_css_blurb_image=”margin:0;”][/et_pb_blurb][/et_pb_column][et_pb_column type=”3_4″ _builder_version=”3.25″ custom_padding=”30px|20px|20px|0px” custom_padding_tablet=”” custom_padding_phone=”0px||30px|20px” custom_padding_last_edited=”on|phone” custom_padding__hover=”|||”][et_pb_text _builder_version=”4.0.2″ text_font=”||||||||” text_line_height=”1.6em”]

Now let's hear from you!

Are you using this script for your Gmail account?

Is this article helpful for you?

Tell us in the comments section below.

[/et_pb_text][/et_pb_column][/et_pb_row][/et_pb_section]

You may also enjoy...

WordPress based membership sites have certain requirements, and make use of certain applications that, in my experience, makes most of the popular hosting providers a poor choice.
Using Digital Access Pass and OptomizePress? Beware of hackers!
Want to learn 7 simple steps to launch your very own affiliate program QUICKLY, with minimal effort and monetary investment? Click to read…
This tutorial will show you how to create a multi-step popup optin form with GravityForms and Divi and connect it to your email marketing app.

163 Responses

  1. When I try to save I get the following error:
    SyntaxError: Invalid or unexpected token (line 4, file “Code.gs”)

    1. Hi Christie,

      Thank you for reaching out.
      It seems that the issue is related with the additional spaces that are added in the message.

      Can you please use the script below instead ( or you can copy the one in the article as I have updated and removed the spaces) :

      function autoReply() {
      var interval = 5; // if the script runs every 5 minutes; change otherwise
      var wkend = [6,0]; // 1=Mo, 2=Tu, 3=We, 4=Th, 5=Fr, 6=Sa, 0=Su
      var wkendMessage = “Hi, Thank you for contacting us. The office is now closed. All emails will be attended to when the office re-opens at 9:00am PST on Monday morning.”
      var wkdayMessage = “Hi! Thank you for your email. The office hours are Mondays – Fridays 9-6pm PST. Thank you for your patience!”;
      var date = new Date();
      var day = date.getDay();
      var hour = date.getHours();
      if (wkend.indexOf(day) > -1 || (day == 5 && hour >= 18)) {
      var timeFrom = Math.floor(date.valueOf()/1000) – 60 * interval;
      var threads = GmailApp.search(‘is:inbox after:’ + timeFrom);
      for (var i = 0; i < threads.length; i++) { threads[i].reply(wkendMessage); } } else if (hour < 9 || hour >= 18) {
      var timeFrom = Math.floor(date.valueOf()/1000) – 60 * interval;
      var threads = GmailApp.search(‘is:inbox after:’ + timeFrom);
      for (var i = 0; i < threads.length; i++) { threads[i].reply(wkdayMessage); } } } Feel free to reach out if you have any other questions. Kind Regards,

      1. I tried this script as i was getting the same error but now i get this error:

        Syntax error: SyntaxError: Invalid or unexpected token line: 4 file: Code.gs

  2. Hi Ardian, this is exactly what I have been searching for. Well done. Now, I have done everything and saved and Deployed as Web App. Would Gmail automatically pick this up? I sent a test message (it’s now Saturday afternoon). But I have not received an automated response. Please tell me what I have done wrong? Thank you.

    (What do I do with this script?)

    https://script.google.com/a/sixfoot5.co.za/macros/s/AKfycbwT7y50nPEGqaIx3Xp554uaItjoz6fmtnDsVKwXv0FwhUZm2P0/exec

      1. Hi Etienne,

        I am glad to hear that you find this useful!
        Unfortunately, I am unable to open the link you have sent.

        Can you please check the timezone of your Google Account, perhaps that’s why you didn’t receive the email, furthermore can you try to send another email from a different account?

        Feel free to reach out if you have any other questions.
        Kind Regards,

  3. Hello Adrian, thnx for the code.
    But when I test the code, I get “Script function not found: doGet”
    What do I need to add to the code?
    Thnx

    1. Hi Eric,

      Apparently saving and republishing your google script web app is not good enough. You need to save a new version and publish the new version to make sure your app gets updated properly.

      Please click Publish>Deploy as Web App> and select “New” in the project version dropbox.

      Feel free to reach out if you have any other questions.
      Kind Regards,

        1. Hi Sheena,

          Thank you for reaching out.
          Unfortunately, I am unable to replicate the issue.
          According to the article you have send you need to add the doGet() function.

          I tried to add the doGet() function at the bottom and I didn’t see any errors. Please check the screenshot here: https://prnt.sc/siv84r

          Try that method and I think you won’t see the error anymore.

          Kind Regards,

          1. Thanks for the quick reply Ardian. This definitely resolved the error. Unfortunately even after following your steps the script deployed, but didn’t seem to be running. I went in and setup a timed trigger for every minute and that seemed to do that trick. Thanks again for all of your help and for posting this. Really appreciate it

          2. Hi Etienne,

            I have sent an email and received the auto response.
            Have you received my email?

            Kind Regards,

          3. Can you post a video on how to do this–I am trying to set ours up. Thank you so much!

  4. sheena and Ardian–can you please post how to add the timed trigger to finish this tutorial.? I have got to the point where I have added lines
    25. function doGet() {
    26. return ContentService.createTextOutput(‘I just successfully handled your GET request.’);
    27. }

    What else is needed? It would be great if you can make a tutorial including the new steps needed to execute this task. Thanks so much!

    1. Hi Amy,

      If you see this error: “Script function not found: doGet”
      By adding the doGet() function at the end as you have done the error will go away.

      Please click Publish > Deploy as Web App > and select “New” in the project version dropbox.

      It seems that the addition of doGet() function is necessary only for some users.
      I was able to deploy the script without doGet() function.

      Feel free to reach out if you have any other questions.
      Kind Regards,

  5. Hi!

    Thanks for this. Really helpfull.

    A quick question, is there a way to kinda temporarly stop the script without having to remove it?

    Many thanks

    Jose

    1. Hi Jose,

      Thank you for reaching out. I am glad that it works fine for you!

      Unfortunately, there doesn’t seem to be a way to stop the script temporarily. The only way at the moment would be to remove the script and add it again when neccesary.

      I hope this helps!

      Kind Regards,

  6. Hi Adrian! Thanks for the tutorial. BUt let me admit I have absolutely no clue about apps script. So I need your help to move further. Now that I have the script ready and error free, what are the next steps that i need to take to get my auto response going?

    1. Hi Sanchita,

      There are no additional steps. The script itself will run and auto-reply every email you get.

      Feel free to reach out if you have any other questions.

      Kind Regards,

  7. This works like charm! Just curious if this involves any cost in terms of #times the script ran or something ?

  8. This solution works like a charm ! However curious to know if there is any cost involved in terms of #times the script is run or anything like that.

    1. Hi Abhay,

      Thank you for reaching out. I am glad that it works fine for you!

      This method is free of charge and you won’t be charged anything by using this script.

      I hope this helps!

      Kind Regards,

  9. Hello- I get this message “The script completed but did not return anything.” any idea how I can resolve this?

    1. Hi Maria,
       
      I believe the doGet() function was empty that’s why you saw that error.
       
       
      Can you please change the doGet() function slightly as shown in the screenshot here: https://prnt.sc/siv84r
       

      function doGet() {
        return ContentService.createTextOutput('I just successfully handled your GET request.');
      }
      

       
      So the script should be added as an addition to the other part of the script.
       
      Kind Regards,

    2. Hello- Thank you for troubleshooting with me. I no longer get that message.. now I get “I successfully handled your GET request.” However, I sent several test emails to see if I get the auto reply and nothing. I’m I doing something incorrectly? This is the doGet()fuction added-
       
      Thank you for the help.

      1. Hi Maria,
         
        May I know if you tried to send the email after your working hours?
        Also, it might take up to 5 minutes to receive the email, perhaps you got the email after a few minutes?
         
        Also, is it possible to change the hours from 730 and 1530 to 7 and 15?
        http://prntscr.com/su7la4
         
        Can you please try again after making these changes.
         
        Kind Regards,
         

  10. function autoReply() {
    var interval = 5; // if the script runs every 5 minutes; change otherwise
    var wkend = [6,0]; // 0=Mo, 1=Tu, 2=We, 3=Th, 4=Fr, 5=Sa, 6=Su
    var wkendMessage = “Hi, Thank you for contacting me. My office is now closed. All emails will be attended to when I resume work at 9:00am AEST on Tuesday morning.”
    var wkdayMessage = “Hi! Thank you for your email. My office hours are Tuesday – Saturday 9-6pm. Thank you for your patience! I will contact you back during working hours”;
     var date = new Date();
     var day = date.getDay();
     var hour = date.getHours();
     if (wkend.indexOf(day) > -1 || (day == 5 && hour >= 18)) {
      var timeFrom = Math.floor(date.valueOf()/1000) – 60 * interval;
      var threads = GmailApp.search(‘is:inbox after:’ + timeFrom);
      for (var i = 0; i < threads.length; i++) {
       threads[i].reply(wkendMessage);
      }
     }
     else if (hour < 9 || hour >= 18) {
      var timeFrom = Math.floor(date.valueOf()/1000) – 60 * interval;
      var threads = GmailApp.search(‘is:inbox after:’ + timeFrom);
      for (var i = 0; i < threads.length; i++) {
       threads[i].reply(wkdayMessage);
      }
     }
    }
     
    function doGet() {
      
     
    I have the Do get problem i try that script doesnt work and comes up with SyntaxError: Unexpected end of input (line 26 file code gs) how do i resolve this

    1. Hi Josh,
       
      Can you please change the doGet() function slightly as shown in the screenshot here: https://prnt.sc/siv84r
       
       
      So additionally this code should be added:
       

      function doGet() {
        return ContentService.createTextOutput('I just successfully handled your GET request.');
      }
      

       
      Please let me know if you have any other issues.
      Kind Regards,
       

  11. Hi Adrian!
    The script is working perfectly, thank you for this amazing solution.
    I’m ZERO code…and I would like to tweak a little the responder message. Maybe add my logo, change the paragraph style. Is there any way you can help me with this? Please feel free to contact me via email, but no during the weekend because I have an auto-responder! ha ha ha

    1. Hi Angelo,
       
      I am glad to hear that is working for you!
       
      Unfortunately, the script doesn’t accept images at the moment and we can’t change the style of the paragraph, you can change the text though.
       
      I know that this may not be quite the answer that you were hoping for, but please let me know if there is anything else that I can help with.
      Kind Regards,

  12. Hello Ardian and Sheena, I got same issue with Sheena. I tried the solutions that you give to sheena and it works. However, when I tried to sent email to the email address I created the script, the autoresponder is not sending the auto reply. May I know what is the timed trigger that I need to add in able for the autoresponder to work, please?

    1. Hi Diana,
       
      The auto-responder will work outside the working hours and during the weekend.
      The script will trigger every 5 minutes.
       
      Please let us know if you have any other questions.
      Kind Regards,

      1. Thank you for responding Ardian. I tried to test it during outside of working hours but it is not working. Did I missed some of the settings? Please help me. I posted this code:
         
        function autoReply() {
        var interval = 5; // if the script runs every 5 minutes; change otherwise
        var wkend = [6,0]; // 1=Mo, 2=Tu, 3=We, 4=Th, 5=Fr, 6=Sa, 0=Su
        var wkendMessage = “Hi, Thank you for contacting us. The office is now closed. All emails will be attended to when the office re-opens at 9:00am PST on Monday morning.”
        var wkdayMessage = “Hi! Thank you for your email. The office hours are Mondays – Fridays 9-6pm PST. Thank you for your patience!”;
         var date = new Date();
         var day = date.getDay();
         var hour = date.getHours();
         if (wkend.indexOf(day) > -1 || (day == 5 && hour >= 18)) {
           var timeFrom = Math.floor(date.valueOf()/1000) – 60 * interval;
           var threads = GmailApp.search(‘is:inbox after:’ + timeFrom);
           for (var i = 0; i < threads.length; i++) {
             threads[i].reply(wkendMessage);
           }
         }
         else if (hour < 9 || hour >= 18) {
           var timeFrom = Math.floor(date.valueOf()/1000) – 60 * interval;
           var threads = GmailApp.search(‘is:inbox after:’ + timeFrom);
           for (var i = 0; i < threads.length; i++) {
             threads[i].reply(wkdayMessage);
           }
         }
        }
        function doGet() {
         return ContentService.createTextOutput(‘I just successfully handled your GET request.’);
        }

        1. Hi Diana,
           
          Can you please change the interval to 1.
          http://prntscr.com/synump
           
          It should be var interval = 1;
           
          When you make the change please click Publish > Deploy as Web App > and select “New” in the project version dropbox.
           
          Kind Regards,

          1. I already changed it to 1. But nothing happens. I hope you can help me fix the problem. What should I choose in Who has access to the app:? Is it only Myself? or Anyone?

          2. Hi Diana,
             
            What should I choose in Who has access to the app:? Is it only Myself? or Anyone?
            That is by default Only Myself, please leave it like that.
             
             
            I am sorry to hear that is not working for you.
             
            I would suggest you to delete the current Project and do the steps again from scratch.
             
            I think this is the only thing left because your script is working fine in my end.
             
            I know that this may not be quite the answer that you were hoping for, but please let me know if there is anything else that I can help with.
            Kind Regards,

          3. Hi Diana, not sure if this is of any use but I came across ‘boomerang’ which lets you pause your inbox, sending out an auto-response, and can be scheduled to ‘un-pause’. I’m using that as an interim as I can’t get this to work. I pause it when i finish work and set it to come back on again the following morning. Works ok so far ????????

          4. Thank you Debbie, I followed all the instruction of Ardian but it’s not working on our end. I’ll check this out and try it. Thanks!

  13. Please help: I (thought) I’d followed your instructions but I’m also not getting an auto response when I send a test email from another account. Any ideas please?

    1. Hi Debbie,
       
      Can you please change the interval to 1.
      http://prntscr.com/synump
       
      It should be var interval = 1;
       
      When you make the change please click Publish > Deploy as Web App > and select “New” in the project version dropbox.
       
      Kind Regards,

      1. Thanks – I did this but still nothing.
        Can you spot anything wrong?
        function autoReply() {
        var interval = 1; // if the script runs every 5 minutes; change otherwise
        var wkend = [6,0]; // 1=Mo, 2=Tu, 3=We, 4=Th, 5=Fr, 6=Sa, 0=Su
        var wkendMessage = “Hi, Thank you for contacting us. It is now outside working hours. All emails will be attended to on Monday morning. Enjoy your weekend!”
        var wkdayMessage = “Hi! Thank you for your email. Our working hours are Mondays – Fridays 9-4pm. Thank you for your patience!”;
         var date = new Date();
         var day = date.getDay();
         var hour = date.getHours();
         if (wkend.indexOf(day) > -1 || (day == 1 && hour >= 16)) {
          var timeFrom = Math.floor(date.valueOf()/1000) – 60 * interval;
          var threads = GmailApp.search(‘is:inbox after:’ + timeFrom);
          for (var i = 0; i < threads.length; i++) {
           threads[i].reply(wkendMessage);
          }
         }
         else if (hour < 9 || hour >= 16) {
          var timeFrom = Math.floor(date.valueOf()/1000) – 60 * interval;
          var threads = GmailApp.search(‘is:inbox after:’ + timeFrom);
          for (var i = 0; i < threads.length; i++) {
           threads[i].reply(wkdayMessage);
          }
         }
        }
            

        1. Hi Debbie,
           
          It seems that you have changed the line below as well:
           
          https://prnt.sc/sz0b22
           
           
          Can you please change it to:
           if (wkend.indexOf(day) > -1 || (day == 5 && hour >= 16)) {
           
          Thank you!

          1. So I now have this and still can’t get it to work?
            Am desperate to get it to work today as I know a client is expecting to book an appointment today for tomorrow…
             
            function autoReply() {
            var interval = 1; // if the script runs every 5 minutes; change otherwise
            var wkend = [6,0]; // 1=Mo, 2=Tu, 3=We, 4=Th, 5=Fr, 6=Sa, 0=Su
            var wkendMessage = “Hi, Thank you for contacting us. It is now outside working hours. All emails will be attended to on Monday morning. Enjoy your weekend!”
            var wkdayMessage = “Hi! Thank you for your email. Our working hours are Mondays – Fridays 9-4pm. Thank you for your patience!”;
             var date = new Date();
             var day = date.getDay();
             var hour = date.getHours();
             if (wkend.indexOf(day) > -1 || (day == 5 && hour >= 16)) {
              var timeFrom = Math.floor(date.valueOf()/1000) – 60 * interval;
              var threads = GmailApp.search(‘is:inbox after:’ + timeFrom);
              for (var i = 0; i < threads.length; i++) {
               threads[i].reply(wkendMessage);
              }
             }
             else if (hour < 9 || hour >= 16) {
              var timeFrom = Math.floor(date.valueOf()/1000) – 60 * interval;
              var threads = GmailApp.search(‘is:inbox after:’ + timeFrom);
              for (var i = 0; i < threads.length; i++) {
               threads[i].reply(wkdayMessage);
              }
             }
            }
               
             

          2. It’s overriding the automatic vacation reply that I just put on, but still not sending out an email. Does it make a difference that it tells me this at the top? This project is running on our new Apps Script runtime powered by Chrome V8
             
             

          3. Hi Debbie,
             
            I am sorry to hear that is not working for you.
            I don’t see any issues on the script.
             
            I would suggest you to delete the current Project and do the steps again from scratch.
             
            I think this is the only thing left because your script is working fine in my end.
             
            I know that this may not be quite the answer that you were hoping for, but please let me know if there is anything else that I can help with.
            Kind Regards,

          4. Thanks – I have tried removing it and starting from scratch but still no joy. Does the banner message at the top affect anything about runtime?

          5. Hi Debbie,
             
            Can you please use the exact same script that we have used and change only the working hours.
            If there would be an issue with the message you would see an error that there is something wrong with the script.
            If the script is published without any errors than the message is fine.
             
            Thank you!

          6. Yes – I have, over 20 times now 🙂 I then remove each one and start over. I do not get an error message at all. I was just asking about the fact that it says it is running on the new apps script and whether this would mean I had to update something somewhere. Clearly if the script is right, and others have managed to get it working, I must have a problem in the saving and running of it so am trying to figure out what as this would be SO helpful to me. Lockdown has blurred the lines for working hours and I am getting a lot of emails on a Sunday and late in the evening which people seem to expect answering. I will follow this thread to see if there are any other solutions. I have searched to find any alternatives and came across the same script posted elsewhere so will persevere and cross fingers that I can get it to work. Thanks for your input 🙂

  14. How do you change it to have start and start and stop times that are not on the hour? I end my day at 3:30.

    1. Hi Robert,
       
      In that case you need to change the code in if statements : https://prnt.sc/t1zm2k

       if (wkend.indexOf(day) > -1 || (day == 5 && hour >= 15)) {
          var timeFrom = Math.floor(date.valueOf()/1000) - 60 * interval;
          var threads = GmailApp.search('is:inbox after:' + timeFrom);
          for (var i = 0; i < threads.length; i++) {
            threads[i].reply(wkendMessage);
          }
        }
        else if (hour < 9 || hour >= 15) {
          var timeFrom = Math.floor(date.valueOf()/1000) - 60 * interval;
          var threads = GmailApp.search('is:inbox after:' + timeFrom);
          for (var i = 0; i < threads.length; i++) {
            threads[i].reply(wkdayMessage);
          }
        }
      }
      

       
      So I am changing it from 18 to 15.
      Unfortunately, you can’t change it to 15:30, it can be either 15 or 16, it’s up to you.
       
      Kind Regards,

    1. How do I change the code to reflect my office hours? I know how to change the message, but how do I program it to only go out during my actual office hours?

  15. Hi

    Like the idea a lot, and I wanna correct a bit, so I will make it read a xml file, that includes information whether I am at work or not. This xml I can write to from my phone, so in this way I can activate / deactivate auto-response from my phone.

    However, I don’t get the concept of the function and the interval. The main function is named autoReply() and the 2nd line is var interval = 5; But does Google just look for the interval variable and run the script every interval minutes? In my little developer world we have defined a function autoReply() but we haven’t defined anywhere, when it should be run.

    Please enlighten me 🙂

    Thanks a million!

  16. I like this script and it works just fine, except now, it responds to ALL of my emails, even noreply emails. Is there a function I can add that will allow me to respond only to certain email domains, or something?

    1. You can create a Google group with a list of all emails you want the response to send to and set the script to only send to users on that list through an if statement.

  17. Hi Ardian,

    Thank you for providing this tutorial, I have 2 questions.

    1. how can you change the time zone in the code, I am in new york, eastern time
    2. my office hours are from 8am-2:30pm, how can i add the extra 30 minutes in the code.
    1. Hello luis,

      You also need to add minutes to your condition:

      var date = new Date();
      var day = date.getDay();
      var hour = date.getHours();
      var minute = date.getMinutes();
      if (wkend.indexOf(day) > -1 || (day == 5 && hour >= 14 && minute >=30 ))
      
      1. Where do you place this additional code in the grander code? I entered it where I thought it went and it stopped the automation from working altogether.

    1. Hello Dani,

      You need to add a time offset:

      var offset = -300; //Timezone offset for EST in minutes.
      var currentDate = new Date();
      var date = new Date(currentDate.getTime() + offset*60*1000);
      
      1. Oops meant to post this here: Where do you place this additional code in the grander code? I entered it where I thought it went and it stopped the automation from working altogether.

  18. I’ve had different people emailing me to test it out. Some have had it work, one time it looked like I sent it to myself, and others just didn’t receive anything… How is that possible? Also, I’m on an all-staff list and it worked then. Is there a way to disable a particular list or spam email from getting the auto reply?

    function autoReply() {
    var interval = 5; // if the script runs every 5 minutes; change otherwise
    var wkend = [6,0]; // 1=Mo, 2=Tu, 3=We, 4=Th, 5=Fr, 6=Sa, 0=Su
    var wkendMessage = “Hi, Thank you for contacting me. I am away from my computer. All emails will be attended to during school hours. If you would like to make an appointment to meet, please follow this link for appointment times. https://wgtvzpplfkkmfrkghx.10to8.com Thank you for your patience!”
    var wkdayMessage = “Hi, Thank you for contacting me. I am away from my computer. All emails will be attended to during school hours. If you would like to make an appointment to meet, please follow this link for appointment times. https://wgtvzpplfkkmfrkghx.10to8.com Thank you for your patience!”;
     var date = new Date();
     var day = date.getDay();
     var hour = date.getHours();
     if (wkend.indexOf(day) > -1 || (day == 5 && hour >= 18)) {
       var timeFrom = Math.floor(date.valueOf()/1000) – 60 * interval;
       var threads = GmailApp.search(‘is:inbox after:’ + timeFrom);
       for (var i = 0; i < threads.length; i++) {
         threads[i].reply(wkendMessage);
       }
     }
     else if (hour < 7 || hour >= 12) {
       var timeFrom = Math.floor(date.valueOf()/1000) – 60 * interval;
       var threads = GmailApp.search(‘is:inbox after:’ + timeFrom);
       for (var i = 0; i < threads.length; i++) {
         threads[i].reply(wkdayMessage);
       }

    I’ve tried both of these with mixed results for both
    function autoReply() {
    var interval = 5; // if the script runs every 5 minutes; change otherwise
    var wkend = [6,0]; // 1=Mo, 2=Tu, 3=We, 4=Th, 5=Fr, 6=Sa, 0=Su
    var wkendMessage = “Hi, Thank you for contacting me. I am away from my computer. All emails will be attended to during school hours. If you would like to make an appointment to meet, please follow this link for appointment times. https://wgtvzpplfkkmfrkghx.10to8.com Thank you for your patience!”
    var wkdayMessage = “Hi, Thank you for contacting me. I am away from my computer. All emails will be attended to during school hours. If you would like to make an appointment to meet, please follow this link for appointment times. https://wgtvzpplfkkmfrkghx.10to8.com Thank you for your patience!”;
     var date = new Date();
     var day = date.getDay();
     var hour = date.getHours();
     if (wkend.indexOf(day) > -1 || (day == 5 && hour >= 18)) {
       var timeFrom = Math.floor(date.valueOf()/1000) – 60 * interval;
       var threads = GmailApp.search(‘is:inbox after:’ + timeFrom);
       for (var i = 0; i < threads.length; i++) {
         threads[i].reply(wkendMessage);
       }
     }
     else if (hour < 7 || hour >= 12) {
       var timeFrom = Math.floor(date.valueOf()/1000) – 60 * interval;
       var threads = GmailApp.search(‘is:inbox after:’ + timeFrom);
       for (var i = 0; i < threads.length; i++) {
         threads[i].reply(wkdayMessage);
       }
     }
    }

    function doGet() {
     return ContentService.createTextOutput(‘I just successfully handled your GET request.’);
    }

  19. Hi there, this is the script I wrote based on the information you provided. However, I keep getting an error: SyntaxError: Invalid or unexpected token (line 5, file “Code.gs”)

    Please let me know what I have done wrong. My business hours are from Monday to Friday from 10am to 5pm, I would need the below script / Auto Responder to run outside of those hours and including weekends.

    Please help me, I look forward to hearing back from you soon!

    Cheers,
    Amen
    [email protected]

    function myFunction() {
     function autoReply() {
    var interval = 1; // if the script runs every 5 minutes; change otherwise
    var wkend = [6,0]; // 1=Mo, 2=Tu, 3=We, 4=Th, 5=Fr, 6=Sa, 0=Su
    var wkendMessage = “Hey there!

    Thank you for your email! I’m sending you this reply as I don’t always respond right away, as with these unprecedented times, our clients are our #1 priority! 

    You can expect a response based on the below information:

    – I am available Monday through Friday, 10AM to 5PM Pacific Standard Time. The office is closed on weekends & all statutory holidays.

    – If you’re a current client of mine, you’re at the top of my list and can expect a response within 24 hours, Monday through Friday. 

    – If you’re inquiring about working together, I can’t wait to learn more about your career needs! I will respond within 24-48 hours Monday through Friday, with details about our services and how to schedule a consultation. 

    – If you’re just wanting to connect, have a question, or looking to collaborate, I so appreciate you taking the time to get in touch! At this time, I’m giving my full attention to my clients and will do my best to make sure you’re taken care of within the week.

    PLEASE NOTE: All email response times exclude weekends, evenings and national holidays. 

    Thanks for understanding, and speak to you soon! 

    Cheers!
    Amen ”
    var wkdayMessage = “Hey there!

    Thank you for your email! I’m sending you this reply as I don’t always respond right away, as with these unprecedented times, our clients are our #1 priority! 

    You can expect a response based on the below information:

    – I am available Monday through Friday, 10AM to 5PM Pacific Standard Time. The office is closed on weekends & all statutory holidays.

    – If you’re a current client of mine, you’re at the top of my list and can expect a response within 24 hours, Monday through Friday. 

    – If you’re inquiring about working together, I can’t wait to learn more about your career needs! I will respond within 24-48 hours Monday through Friday, with details about our services and how to schedule a consultation. 

    – If you’re just wanting to connect, have a question, or looking to collaborate, I so appreciate you taking the time to get in touch! At this time, I’m giving my full attention to my clients and will do my best to make sure you’re taken care of within the week.

    PLEASE NOTE: All email response times exclude weekends, evenings and national holidays. 

    Thanks for understanding, and speak to you soon! 

    Cheers!
    Amen ”;
    var date = new Date();
    var day = date.getDay();
    var hour = date.getHours();
    if (wkend.indexOf(day) > -1 || (day == 10 && hour >= 17)) {
    var timeFrom = Math.floor(date.valueOf()/1000) – 60 * interval;
    var threads = GmailApp.search(‘is:inbox after:’ + timeFrom);
    for (var i = 0; i < threads.length; i++) {
    threads[i].reply(wkendMessage);
    }
    }
    else if (hour = 18) {
    var timeFrom = Math.floor(date.valueOf()/1000) – 60 * interval;
    var threads = GmailApp.search(‘is:inbox after:’ + timeFrom);
    for (var i = 0; i < threads.length; i++) {
    threads[i].reply(wkdayMessage);
    }
    }
    }
    function doGET() {
     return ContentService.createTextOutput(‘I just successfully handled your GET request.’);
    }
    }

  20. Ardian,
    I am hoping you can help! When I test the web app for the latest code, I receive the error: Script function not found: doGet
    Suggestions please?
    Thank you so much,
    Heather

    1. Hello Heather,

      Every webapp in Google Apps Script must have a main function called doGet() which is the entry point of the app, the function that your app will start with when you type the webapp URL.

      This is true for every application deployed as a standalone app and called by its url – with a user interface or not.

      So you need to just use a function called “doGet” from which you start your program execution.

    1. I had to manually add a timed trigger to make it work (not in the code). Click Edit – current projects trigger – … and then add one from that page.

  21. When i do this, it sends myself a copy of the email over an over again every minute. how do i prevent this from spamming my inbox with email?

      1. same for me
        here is my script

        function autoReply() {
        var interval = 5// if the script runs every 5 minutes; change otherwise
        var wkend = [6,0]; // 1=Mo, 2=Tu, 3=We, 4=Th, 5=Fr, 6=Sa, 0=Su
        var wkendMessage = “Hello, Thank you for your email. The office is now closed. All emails will be attended to when the office re-opens at 8:30 am on Monday morning. Thank you for your patience!”
        var wkdayMessage = “Hello, Thank you for your email. The working hours are Mondays – Fridays 8:30am -17:30pm. Thank you for your patience!”;
          var date = new Date();
          var day = date.getDay();
          var hour = date.getHours();
          if (wkend.indexOf(day) > –1 || (day == 5 && hour >= 1730)) {
            var timeFrom = Math.floor(date.valueOf()/1000) – 60 * interval;
            var threads = GmailApp.search(‘is:inbox after:’ + timeFrom);
            for (var i = 0i < threads.lengthi++) {
              threads[i].reply(wkendMessage);
            }
          }
          else if (hour < 830 || hour >= 1730) {
            var timeFrom = Math.floor(date.valueOf()/1000) – 60 * interval;
            var threads = GmailApp.search(‘is:inbox after:’ + timeFrom);
            for (var i = 0i < threads.lengthi++) {
              threads[i].reply(wkdayMessage);
            }
          }
        }
        function doGet() {
         return ContentService.createTextOutput(“”);
        }

    1. The solution I found for this is once the auto responder is sent have your script mark the message as read. The script is set up to run for any new emails after a certain hour of the day, so if the email is not marked read the script will send the auto reply on a loop.

  22. Hi, when I tried this I got this error ” This app isn’t verifiedThis app hasn’t been verified by Google yet. Only proceed if you know and trust the developer.” Please help

  23. Hi Ardian,

    I tried setting up the script and got this error: Authorization required
    Out of Office Script needs your permission to access your data on Google.

    I “reviewed my permissions”, was able to set it up, ran it as a web app, but I’m not getting any email responses when I send a test from another account.

    Could you please help me figure out how to fix this? Thank you.

    1. Additionally, when I test the app directly from the Script Dashboard I get this error: Script function not found: doGet.

      Thank you.

      1. Hello Belen,

        Do you have the next function in the end of the script:

        function doGet() {
         return ContentService.createTextOutput(””);
        }

        If not, please add it and try again.

  24. Well after spending HOURS and HOURS on trying to get my gmail auto reply working, there were some crucial steps that were missing in your guide, which would have saved me from so much stress! I want to help others who are also finding themselves in my situation by sharing what I did. I also found a way to add line spacing to the plain text which will at least provide a more semi-professional reply, instead of an extremely long line of unformatted text.

    Here is a copy of my working script:

    function autoReply() {
    var interval = 1; // if the script runs every 5 minutes; change otherwise
    var wkend = [6,0]; // 1=Mo, 2=Tu, 3=We, 4=Th, 5=Fr, 6=Sa, 0=Su
    var wkendMessage = “Hello and thank you for taking the time to contact us, however our office is currently closed for the weekend. \n”
    + “\n”
    + “Your email is important to us and we will aim to respond to your matter when we return to work on Monday morning. \n”
    + “\n”
    + “Regards, \n”
    + “\n”
    + “Company Name \n”
    + “www.yourwebsite.com.au”;
    var wkdayMessage = “Hello and thank you for your email. \n”
    + “\n”
    + “You have currently reached us outside our normal office hours, and we are unable to attend to your email right away. \n”
    + “\n”
    + “We appreciate your patience and we will aim to respond to you as soon as possible. \n”
    + “\n”
    + “Regards, \n”
    + “\n”
    + “Company Name \n”
    + “www.yourwebsite.com.au”;
     var date = new Date();
     var day = date.getDay();
     var hour = date.getHours();
     if (wkend.indexOf(day) > -1 || (day == 5 && hour >= 6)) {
       var timeFrom = Math.floor(date.valueOf()/1000) – 60 * interval;
       var threads = GmailApp.search(‘is:inbox after:’ + timeFrom);
       for (var i = 0; i < threads.length; i++) {
         threads[i].reply(wkendMessage);
       }
     }
     else if (hour < 7 || hour >= 17) {
       var timeFrom = Math.floor(date.valueOf()/1000) – 60 * interval;
       var threads = GmailApp.search(‘is:inbox after:’ + timeFrom);
       for (var i = 0; i < threads.length; i++) {
         threads[i].reply(wkdayMessage);
       }
     }
    }

    function doGet() {
     return ContentService.createTextOutput(”);

    So the same rules apply as before – edit the script according to the times you require, my weekday hours are 7am – 5pm, and you can also edit the wording to suit your needs. You will notice that a \n indicates “new line”, your text must be inside “quotation marks” on each line and each additional line must start with a plus +. Once finished, close your message with a semicolon ;

    For example:

    var wkdayMessage = “this is my first line \n”
    + “this is my second line \n”
    + “\n”
    + “This is my fourth line, because the above line is a blank line \n”
    + “This is my final line \n”;

    Now the crucial step for me was, once you setup the script and publish it, you need to manually specify the triggers.
    Go back into “My Projects” on the dashboard > click the 3 dots next to the project name > select Triggers, and then you will notice an + Add Triggers button will appear at the bottom right)

    I used the following options:

    Choose which function to run – Autoreply
    Which runs at deployment – Head
    Select Event Source – Time-Driven
    Select type of time based trigger – Minutes Times
    Select Minute Interval – Every Minute                
    Failure Notification Settings – Notify me daily

    **Obviously you can change these settings to suit your needs

    Once I added these triggers, the script was executing perfectly and the auto reply email text was spaced out over several lines.

    I really hope this helps someone save hours of their day and thanks for providing the original script, because without it, I would not be able to get this running.

    1. Thanks Melissa! Just curious – what time zone are you in? Is the example code based on UTC time (so PST would need to be offset by -480 minutes?)

      I only ask because I pasted this code but would get automated replies BEFORE the end time I set.

      1. My experience with this script as well as the original was that the unexpected or invalid token was the quotation marks. It’s not that they don’t belong, but for some reason, the marks in the examples on this web page don’t always get interpreted properly by the script editor. By replacing the marks with ones from my keyboard, the errors were resolved for me. This also applies to other punctuation like dashes (-) and semi-colons (;)

    2. Thank you Melissa — Your script worked great after a few punctuation tweaks that did not translate well to the script editor from this web page. Both the original script and your tweaks copied quotation marks, dashes, and semi-colons to my editor that my editor didn’t want to recognize. After retyping those marks, the script worked well.

      I did have to change the var Interval to 5 instead of 1 since I run every 5 minutes. Your carriage returns were just what I was looking for!!

    3. When I tried to save the code, I got this: Syntax error: SyntaxError: Invalid or unexpected token line: 5 file: Code.gs
      This is what line 5 shows: (copied from your code above):
      var wkendMessage = Hello and thank you for taking the time to contact ushowever our office is currently closed for the weekend\n

      1. Also, we’re in Eastern time zone. I’m trying to double check where I change the hours of operation.

        BTW -I’ve programmed in BASIC, ages ago, done HTML, but this type of script is new for me.

    4. I just did it. I tested it but it kept coming back to my email every 5 minutes with the same prompt. I changed it to 12 hours?

  25. Unfortunately nothing works for me. can Someone please let us know how to set Office hours with autoreply google script?
    I would greatly appreciate your support on this

      1. Hello Victor

        Thank you for coming back to this.

        Following the updated post, it works!

        Thank you very much in advance
        George

      2. HEllo Victor!

        The email keep sending the autoreply message to himself everyminute.

        Is this normal? haha

        which trigger should i choose for not sending every minute?
        Thank you so much

        1. Hello George,

          Please try to change this parameter:

          Select Minute Interval – Every Minute         
          to
          Every 5 Minutes

          Also, it can be caused if you get an email from yourself on a day off or out of working time. It will launch the chain of emails that will be sent to your mail. Just eliminate it and this issue will be solved.

    1. Hello Justin
      ,
      You need to add a time offset:

      var offset = -360; //Timezone offset for CST in minutes.
      var currentDate = new Date();
      var date = new Date(currentDate.getTime() + offset*60*1000);
      
      1. Hello Victor,

        Thank you for coming back to this.

        The main thing that confuses me, is that the autoreply operation does not responds to the mails. While testing the script that

          1. Yes after I also added this timezone offset code, the script won’t throw errors, but also doesn’t send any automated replies AT ALL, even after the set end time hours. I had the same issue

          2. So after testing the getHours() function in W3schools (https://www.w3schools.com/jsref/jsref_gethours.asp) I found that the function pulled my local time. So is the offset for timezone necessary?

            The offset code did not work for me (PST, -480), and the original code does work but works all the time; in other words, I receive auto replies before the actual end time I’ve set

  26. I can’t get the script to work. It’s Saturday and I sent emails to all three of my email accounts with this script and I’m getting no auto response. I did everything stated in your instructions but it’s not working. Does this send a auto response on weekends??

    1. Hello Chris,

      Yes, it has to send an auto-response on Saturday and Sunday.

      Did you change anything on the script?

      Did you any errors while publishing the script?

  27. Hi there, I keep getting the same errors the others are getting.

    My office hours are Monday to Thursday, 8:00am to 4:00pm EST and Fridays 8:00 to 12:00pm EST.
    I keep getting an error that says “Syntax error: SyntaxError: Invalid or unexpected token line: 4 file: Code.gs”
    Here’s my code:
    function autoReply() {
    var interval = 5; // if the script runs every 5 minutes; change otherwise
    var wkend = [6,0]; // 1=Mo, 2=Tu, 3=We, 4=Th, 5=Fr, 6=Sa, 0=Su
    var wkendMessage = “Hello, and thank you for contacting us. Our office is now closed. All emails will be attended to when the office re-opens at 8:00am EST on Monday morning.”
    var wkdayMessage = “Hello and thank you for your email. Our office hours are Monday to Thursday, 8:00am to 4:00pm EST and Fridays 8:00am to 12:00pm EST. Thank you for your patience!”;
    var date = new Date();
    var day = date.getDay();
    var hour = date.getHours();
    if (wkend.indexOf(day) > –1 || (day == 8 && hour >= 16)) {
    var timeFrom = Math.floor(date.valueOf()/1000) – 60 * interval;
    var threads = GmailApp.search(‘is:inbox after:’ + timeFrom);
    for (var i = 0; i < threads.length; i++) {
    threads[i].reply(wkendMessage);
    }
    }
    else if (hour < 8 || hour >= 16) {
    var timeFrom = Math.floor(date.valueOf()/1000) – 60 * interval;
    var threads = GmailApp.search(‘is:inbox after:’ + timeFrom);
    for (var i = 0; i < threads.length; i++) {
    threads[i].reply(wkdayMessage);
    }
    }
    }
    function doGet() {
     return ContentService.createTextOutput(”“);
    }

    1. Hello Mike,

      You missed “;” in this line:

      var wkendMessage = “Hello, and thank you for contacting us. Our office is now closed. All emails will be attended to when the office re-opens at 8:00am EST on Monday morning.”

  28. Hi Everyone – can someone help me customize this to be sending one message from Monday to Sunday – outside the hours of 8am and 6pm? It works every weekday but I could not figure out how to eliminate the weekend conditions

    Thank you!

    1. Hello Mae,

      You need to remove this condition:

      if (wkend.indexOf(day) > -1 || (day == 5 && hour >= 18)) {
          var timeFrom = Math.floor(date.valueOf()/1000) - 60 * interval;
          var threads = GmailApp.search('is:inbox after:' + timeFrom);
          for (var i = 0; i < threads.length; i++) {
            threads[i].reply(wkendMessage);
          }
        }
      
  29. Hi, thanks for this script. It was exactly what I was looking for.
    But for some reason I received an auto reply myself every minute, woke up this morning to 1500 emails from myself.
    And is it possible to exclude certain recipients from getting the auto reply message?

      1. I had the same problem… but I think I figured it out – When setting up your trigger, the settings above say “Select Minute Interval – Every Minute” but the code is written to run every five minutes… so it’s spamming our inboxes. Change your trigger setting to run every five minutes so it matches the script.

        1. Hello Bea,

          You are partly right. It’s because of the not synchronized script.

          Also, you can start getting emails for each email you send to yourself. So you can eliminate this sequence and it will stop.

        2. That doesn’t seem to work for me. Its lessened so I’m not getting an email duplicated to me every minute, but now it’s every 5 minutes.

  30. Thanks for sharing this code!

    I do have a question. I changed the closing hour to 16 (4pm) and sent myself an email from a different account BEFORE 4pm to test. It was 3:48pm and I received an auto reply.

    Any suggestions on what happened and how to fix this?

    1. This is what the code looks like:

      if (wkend.indexOf(day) > -1 || (day == 5 && hour >= 16)) {
      var timeFrom = Math.floor(date.valueOf()/1000) – 60 * interval;
      var threads = GmailApp.search(‘is:inbox after:’ + timeFrom);
      for (var i = 0; i < threads.length; i++) {
      threads[i].reply(wkendMessage);
      }
      }
      else if (hour = 16) {
      var timeFrom = Math.floor(date.valueOf()/1000) – 60 * interval;
      var threads = GmailApp.search(‘is:inbox after:’ + timeFrom);
      for (var i = 0; i < threads.length; i++) {
      threads[i].reply(wkdayMessage);
      }
      }

      *Note that I only changed 18 to 16 – everything else is exactly copied from above

      1. if (wkend.indexOf(day) > -1 || (day == 5 && hour >= 16)) {
        var timeFrom = Math.floor(date.valueOf()/1000) – 60 * interval;
        var threads = GmailApp.search(‘is:inbox after:’ + timeFrom);
        for (var i = 0; i < threads.length; i++) {
        threads[i].reply(wkendMessage);
        }
        }
        else if (hour = 16) {
        var timeFrom = Math.floor(date.valueOf()/1000) – 60 * interval;
        var threads = GmailApp.search(‘is:inbox after:’ + timeFrom);
        for (var i = 0; i < threads.length; i++) {
        threads[i].reply(wkdayMessage);
        }
        }

        This is what I meant to paste – I'm honestly not sure how that code (else if(hour = 16)) was pasted from above. It doesn't say that anywhere in my code, so I may have accidentally backspaced as I wrote the comment.

    2. I didn’t realize I needed to add the time offset, especially since the text in the example mentioned PST (which is where I am). I think the offset should be mentioned in the actual article, along with many examples. The comments were very helpful!

      1. Hi Alexandra, would you be kind to share what I need to add to script to get the reply in my timezone? mine is CET or GMT+1 and my out of office reply started arriving in my working hours? I can not find where in the script and how to set the correct timezone? thank you in advance

  31. hi, I have copy/pasted the code without an modification just to try it and I get this error:
    Syntax error: SyntaxError: Invalid or unexpected token line: 25 file: Code.gs

    image attached

    1. after several tries, deleting code and getting it back it saved it….but now I ger replies in my working times instead of closing hours? where do I add the timezone?
      thanks

      1. I tried adding the timezone, thinking it had worked – but now I do not get any automated replies even AFTER the time. When I remove the code for the timezone offset, I get replies, but I also get replies BEFORE the end time I set. So I still don’t know what is going on.

        The offset is calculated in minutes difference from UTC (GMT), so since CET is one hour ahead it would be 60.

        It was recommended to paste this in the lines before the if/else statements, where you see var date = new Date(); (you will have to remove that or // comment it out)

        The code for the offset provided by Victor Barannik:
        var offset = 60; //Timezone offset for CET in minutes.
        var currentDate = new Date();
        var date = new Date(currentDate.getTime() + offset*60*1000);

        That being said, this still isn’t working for me, and it looks like it wasn’t working for someone else above. Stayed tuned for more

  32. I have made a script to automatically reply when I’m outside of working hours. The sender receive one message from me, as expected. However, I am getting an email with the same content every minute, until I actually read the customer email.
    I do not want to mark the email as read until I actually read it.
    Is there a solution of stopping sending these emails? Thank you!

  33. Okay. So I have the script running, and it works. HOWEVER it keeps replying. To me.

    So it replies to the initial email once , and then it keeps sending the reply to me (every minute), not the initial sender (luckily). I have added a code to label the emails that it replies to to be marked as read and important, which I think is why it at least isn’t replying to the sender of the original email.

    1. It seems to me that there are many ‘doom loops’ in this code.

      Example:

      1. You get an email from an email address that does not handle replies.
      2. You reply with the code in this script
      3. The reply is bounced with an ‘unknown recipient’ message from an email address which also does not handle replies
      4. You reply with the code in this script
      5. Goto step 2.
  34. Adrian,

    Thank you for posting this script. Just so your readers like me who do not know scripting can understand if they get errors at punctuation, if you copy and paste the script into your editor, the punctuation marks sometimes get misinterpreted by the editor. Just replace the red underlined marks with ones from your keyboard, and then they should work.

    Thanks to Melissa who brought up the “\n” command to insert “carriage returns” (showing my age).

  35. I wrote a script that switches your GMail Out of Office Autoresponder on and off depending whether there is an Out of the Office event in your calendar. (Note that OOTO Calendar events are not available for ‘free’ google accounts.

    This means that your script can use the GMail GUI for creating your OOTO message, you do not need to hard code it into your script.

    /**
     * Looks <interval> minutes into the past and the future for OOTO entries in the Calendar
     * <interval> currently set as 15 minutes in the code
     * This script should be triggered to run for double the interval setting (e.g. 30 minutes if interval is 15)
     * 
     * Sets GMail Out-of-Office AutoReply ON if there is a current OOTO event in the primary calendar
     * or an OOTO is due to start within the next <interval>
     * Aligns the GMail Vacation start and end date with the Calendar OOTO date/timestamp
     * 
     * Sets GMail Out-of-Office AutoReply OFF if there is no current OOTO event in the calendar
     * or an existing one will end during this <interval>
     * 
     * The script DOES NOT CHANGE the GMail vacation responder options for domain emails and the user's Contacts
     * Behaviour of the above is not what you might expect
     * See https://support.google.com/a/thread/103802728?hl=en
     * The script DOES NOT CHANGE the GMail vacation responder subject title or message contents
     * These should be set manually by the user in the GMail settings
     *
     * NOTE: Gmail uses rounding to display vacation start and end times to the nearest DAY
     * in the GMail settings GUI. This script sets the start and end times to be identical to
     * the OOTO event start and end time. Gmail settings GUI do NOT display these as you might expect
     * but testing has shown that they are being used correctly
     * 
     * PROVIDED WITHOUT WARRANTY OR SUPPORT
     * 
     */
    
    
    function syncCalendarOOTOWithGMailOOTOAutoReply () {
    
    
      var interval = 15 // minutes
    
    
      /**
       * Get the API response for events between
       * <interval> minutes in the past
       * and <interval> minutes in the future
       */
    
    
      var now = new Date();
      var nowMinusInterval = new Date(now.getTime() - (interval * 60 * 1000));
      var nowPlusInterval = new Date(now.getTime() + (interval * 60 * 1000));
      var calendarId = 'primary';
      var optionalArgs = {
        timeMin: nowMinusInterval.toISOString(),
        timeMax: nowPlusInterval.toISOString(),
        showDeleted: false,
        singleEvents: true,
        orderBy: 'startTime'
      };
      var response = Calendar.Events.list(calendarId, optionalArgs);
      
      // Get the events from the response
      var events = response.items;
      // Debug: console.log('Number of events: ' + events.length);
      // Do nothing if there are no events
      if (events.length > 0) {
        // For each event (until an OOTO event is handled)
        for (i = 0; i < events.length; i++) {
          var event = events[i]
          // Debug: Logger.log('Event: ' + i);
          // if I am the creator, I am NOT the organizer 
          // Organizer is [email protected]
          // https://developers.google.com/calendar/releases#february_8_2021
          if (event.creator.self) {
            if (event.eventType == "outOfOffice" ) {
              /**
               * Need to handle this
               * Test about to start, already started, or about to end
               * Use break to exit if an OOTO is handled
               */
              // Debug: Logger.log('Event start: ' + event.start.dateTime);
              // Debug: Logger.log('Event end: ' + event.end.dateTime);
              var startOOTO = new Date(event.start.dateTime);
              var endOOTO = new Date(event.end.dateTime);
              
              var vacationSettings = Gmail.Users.Settings.getVacation("me");
              /**
                https://developers.google.com/gmail/api/reference/rest/v1/VacationSettings
                'enableAutoReply': true,
                'restrictToContacts': true,
                'restrictToDomain': true,
                'startTime': startOOTO.getTime(),
                'endTime': endOOTO.getTime()
               */
    
    
              // Is OOTO due to start in this interval window?
              // OR is now after an OOTO start and before an OOTO finish
              if (vacationSettings.enableAutoReply != true) {
                if (
                  ((nowMinusInterval <= startOOTO) && (startOOTO <= nowPlusInterval))
                  || ((now >= startOOTO) && (now <= endOOTO))) {
                  // Switch GMail vacation settings on
                  vacationSettings.enableAutoReply = true;
                  /** These settings don't work the way you might think, so they are commented out
                   * Chooose your own settings in the GMail Settings
                   * vacationSettings.restrictToContacts = true;
                   * vacationSettings.restrictToDomain = true;
                   */
                  vacationSettings.startTime = startOOTO.getTime();
                  vacationSettings.endTime = endOOTO.getTime();
                  // Debug: Logger.log('Autoresponder ON');
                  // Debug: Logger.log('Vacation start: ' + vacationSettings.startTime);
                  // Debug: Logger.log('Vacation end: ' + vacationSettings.endTime);
                  Gmail.Users.Settings.updateVacation(vacationSettings,"me");
                  // No need to check any more events
                  break;
                }
              }
    
    
              // Is OOTO due to end in this interval window?
              if ((nowMinusInterval <= endOOTO) && (endOOTO <= nowPlusInterval)) {
                // Switch GMail vacation settings off
                vacationSettings.enableAutoReply = false;
                Logger.log('Autoresponder OFF');
                // Debug: Logger.log('Vacation start: ' + vacationSettings.startTime);
                // Debug: Logger.log('Vacation end: ' + vacationSettings.endTime);
                Gmail.Users.Settings.updateVacation(vacationSettings,"me");
                // No need to check any more events
                break;
              }
            }
          }
        }
      }
    }
    
  36. This was very helpful, thank you!

    Now if only there were a way to link it to a series of calendar events?

  37. This helps me lot. Thank you! What could I do if I don’t want to autoreply emails from specific email address?

  38. Hello, the script has no errors but once someone has emailed me in the allotted time, it autoreply’s to me(from me) afterwards sending me up to 100 emails stating my after hours message, here’s my code. Not sure if i did something wrong. It seems if the email is left unread, then it Autoreply’s to myself until I’ve opened the email.

    function autoReply() {
    var interval = 5; // if the script runs every 5 minutes; change otherwise
    var wkend = [6,0]; // 1=Mo, 2=Tu, 3=We, 4=Th, 5=Fr, 6=Sa, 0=Su
    var wkendMessage = “Hello and thank you for taking the time to contact me, I will respond during school working hours. Have a great day”;
    var wkdayMessage = “Hello and thank you for taking the time to contact me, I will respond during school working hours. Have a great day”;
    var date = new Date();
    var day = date.getDay();
    var hour = date.getHours();
    if (wkend.indexOf(day) > -1 || (day == 5 && hour >= 18)) {
    var timeFrom = Math.floor(date.valueOf()/1000) – 60 * interval;
    var threads = GmailApp.search(‘is:inbox after:’ + timeFrom);
    for (var i = 0; i < threads.length; i++) {
    threads[i].reply(wkendMessage);
    }
    }
    else if (hour = 18) {
    var timeFrom = Math.floor(date.valueOf()/1000) – 60 * interval;
    var threads = GmailApp.search(‘is:inbox after:’ + timeFrom);
    for (var i = 0; i < threads.length; i++) {
    threads[i].reply(wkdayMessage);
    }
    }
    }
    function doGet() {
    return ContentService.createTextOutput("");
    }

  39. Thank you for this! It works great! However, the auto-reply message is sent out in boring Arial font. Is there a way to change the font of the auto-reply to the font we have set for our e-mail?

  40. It seems like the fatal flaw of this script is the continuous looping of auto reply messages. For example I received an email that it auto responded ot, and then that email itself had an auto responder, then this script replied back to that… you can see where I’m going with this. I’m not sure if there is a way to make it only respond ONCE per sender like the actual vacation responder does, otherwise this is useless.

    1. I made a much more betterer one after finding the same flaw.
      Plugged it together from multiple sources, and lets you customise the message with a HTML file in your Drive root.

      You need two triggers though:
      https://stackoverflow.com/a/68458557

      I just can’t figure out why I can’t embed a base64 image into it though.

      function initializeLogs(){
        //Get Script properties
        var scriptProperties = PropertiesService.getScriptProperties();
        scriptProperties.setProperty('email','');
      }
      
      
      function autoReply() {
          //Get Script properties
        var scriptProperties = PropertiesService.getScriptProperties();
        var emailLogs = scriptProperties.getProperty('email');
        Logger.log(emailLogs);
      
      
      var interval = 1; // if the script runs every 5 minutes; change otherwise
      var wkend = [6,0]; // 1=Mo, 2=Tu, 3=We, 4=Th, 5=Fr, 6=Sa, 0=Su
      
      
          // get html message
      
              var files = DriveApp.getRootFolder().getFilesByName('autoreply.html');
          var htmlbody;
          while (files.hasNext()) {
            var file = files.next();
      
      
            htmlbody = file.getBlob().getDataAsString('utf8');
      }
      
      
      
        var date = new Date();
        var day = date.getDay();
        var hour = date.getHours();
      
      
      
      
      
        if (wkend.indexOf(day) > -1 || (day == 5 && hour >= 17)) {
          var timeFrom = Math.floor(date.valueOf()/1000) - 60 * interval;
          var threads = GmailApp.search('is:inbox after:' + timeFrom);
      
      
      for (let mess of threads) {
          if (mess.getMessageCount() == 1) {
          
            //get email address of the message sender
            var sender = mess.getMessages()[0].getFrom();
      
      
            if(!emailLogs.includes(sender)){
              Logger.log(sender);
              //sender not yet in the logs, send reply
            mess.reply("", {
                htmlBody: output
              });
               //add sender to the logs
              scriptProperties.setProperty('email', emailLogs+sender)
                  }
          }
        }
        }
        else if (hour < 8 || hour >= 17) {
          var timeFrom = Math.floor(date.valueOf()/1000) - 60 * interval;
          var threads = GmailApp.search('is:inbox after:' + timeFrom);
      for (let mess of threads) {
          if (mess.getMessageCount() == 1) {
          
            //get email address of the message sender
            var sender = mess.getMessages()[0].getFrom();
      
      
            if(!emailLogs.includes(sender)){
              Logger.log(sender);
              //sender not yet in the logs, send reply
            mess.reply("", {
                htmlBody: htmlbody
              });
      
      
           //add sender to the logs
              scriptProperties.setProperty('email', emailLogs+sender)
              }
          }
        }
        }
      }
      function doGet() {
       return ContentService.createTextOutput("");
      }
      
      1. Jeremy, thanks for your code. It saved with no error. So how do I create the HTML file, I have never worked with root drive and can barely code. I can copy and paste though! Steve

        1. No worries Steve,

          It’s just a web html file called “autoreply.html” saved in the top level of your Drive.

          By that, I mean it’s not in any folders, and it’s just there under the Files section.

      2. Hi, Jeremy. I tried using your code. It sent an autoreply but the email reply was empty. What could have been the problem?

        1. Hi, Jeremy. I tried using your code. It sent an autoreply but the email reply was empty. What could have been the problem?

  41. NEED HELP: My time zone is UTC +8 but I have to follow the PST time, what can I do to make the code follow the PST time?

  42. Thank you for this.
    Work like a charm. However, I have a question. I have a system that creates tickets from emails and I’m creating a loop when the script is working, how could I make this to work with all the incoming emails, except for this particular email address?

    Thank you

  43. Hi, I work Tues-Thurs, 8:15am to 5pm, so I’ve adapted the script. But then noticed that at my work email I got 17 messages in 17 minutes about the email I had sent to my work email from my personal email, Any ideas?

    function autoReply() {
    var interval = 5; // if the script runs every 5 minutes; change otherwise
    var wkend = [1,5,6,0]; // 1=Mo, 2=Tu, 3=We, 4=Th, 5=Fr, 6=Sa, 0=Su
    var wkendMessage = “Hi. Thank you for contacting me. As I work part-time, I will attend to emails during my working days (Tuesdays, Wednesdays & Thursdays).”;
    var wkdayMessage = “Hi. Thank you for your email. I will attend to emails when I am next onsite (Tues-Thurs, 8:15am to 5pm). I thank you in advance for your understanding and patience.”;
    var date = new Date();
    var day = date.getDay();
    var hour = date.getHours();
    if (wkend.indexOf(day) > -1 || (day == 5 && hour >= 17)) {
    var timeFrom = Math.floor(date.valueOf()/1000) – 60 * interval;
    var threads = GmailApp.search(‘is:inbox after:’ + timeFrom);
    for (var i = 0; i < threads.length; i++) {
    threads[i].reply(wkendMessage);
    }
    }
    else if (hour = 17) {
    var timeFrom = Math.floor(date.valueOf()/1000) – 60 * interval;
    var threads = GmailApp.search(‘is:inbox after:’ + timeFrom);
    for (var i = 0; i < threads.length; i++) {
    threads[i].reply(wkdayMessage);
    }
    }
    }
    function doGet() {
    return ContentService.createTextOutput("");
    }

  44. Can anyone help me alter the script for responding different times Saturdays and Sundays? My office is open 8am-12pm Saturday and closed Sunday.

  45. First of all, thank you so much for writing this script!
    I was wondering if there’s a way to make it only apply to direct emails. I’m on an email group at work that redirects emails to me and ideally, I’d like the auto-reply to work only when I’m emailed directly, is that possible?

    And on another note, I also had an issue with the script, it didn’t auto-reply to all the emails I received between the marked times, only to a couple. I checked the timezone and it was correct, so I don’t know what could be happening there. Any ideas?
    Thanks!!

  46. Hi guys, I would like to know if there is a way to only send the automated replies only once for 1 email thread? Meaning like only send it once when they send in the email for the 1st time, and not replying to the thread.

  47. I am getting this error when i try to save:

    Syntax error: SyntaxError: Invalid or unexpected token line: 25 file: Code.gs

Leave a Reply

Your email address will not be published. Required fields are marked *