Manage vacation settings with the Gmail API
Stay organized with collections
Save and categorize content based on your preferences.
This document explains how to use the vacation responder in the Gmail API.
You can use the
settings resource to
configure an automatic reply for an account.
For information on how to
get or
update
vacation responder settings, see the
settings resource.
Configure automatic reply
Automatic reply requires a response subject and body in either HTML or plain
text. These are set using the
VacationSettings
object. You can enable automatic reply indefinitely or limit it to a specific
period of time. You can also restrict automatic reply to known contacts or
domain members.
The following code samples show how to set an automatic reply for a fixed period of time and restrict replies to users in the same domain:
Java
importcom.google.api.client.googleapis.json.GoogleJsonError; importcom.google.api.client.googleapis.json.GoogleJsonResponseException; importcom.google.api.client.http.HttpRequestInitializer; importcom.google.api.client.http.javanet.NetHttpTransport; importcom.google.api.client.json.gson.GsonFactory; importcom.google.api.services.gmail.Gmail; importcom.google.api.services.gmail.GmailScopes; importcom.google.api.services.gmail.model.VacationSettings; importcom.google.auth.http.HttpCredentialsAdapter; importcom.google.auth.oauth2.GoogleCredentials; importjava.io.IOException; importjava.time.LocalDateTime; importjava.time.ZoneOffset; importjava.time.ZonedDateTime; /* Class to demonstrate the use of Gmail Enable Auto Reply API*/ publicclass EnableAutoReply{ /** * Enables the auto reply * * @return the reply message and response metadata. * @throws IOException - if service account credentials file not found. */ publicstaticVacationSettingsautoReply()throwsIOException{ /* Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for your application. */ GoogleCredentialscredentials=GoogleCredentials.getApplicationDefault() .createScoped(GmailScopes.GMAIL_SETTINGS_BASIC); HttpRequestInitializerrequestInitializer=newHttpCredentialsAdapter(credentials); // Create the gmail API client Gmailservice=newGmail.Builder(newNetHttpTransport(), GsonFactory.getDefaultInstance(), requestInitializer) .setApplicationName("Gmail samples") .build(); try{ // Enable auto reply by restricting domain with start time and end time VacationSettingsvacationSettings=newVacationSettings() .setEnableAutoReply(true) .setResponseBodyHtml( "I am on vacation and will reply when I am back in the office. Thanks!") .setRestrictToDomain(true) .setStartTime(LocalDateTime.now() .toEpochSecond(ZoneOffset.from(ZonedDateTime.now()))*1000) .setEndTime(LocalDateTime.now().plusDays(7) .toEpochSecond(ZoneOffset.from(ZonedDateTime.now()))*1000); VacationSettingsresponse=service.users().settings() .updateVacation("me",vacationSettings).execute(); // Prints the auto-reply response body System.out.println("Enabled auto reply with message : "+response.getResponseBodyHtml()); returnresponse; }catch(GoogleJsonResponseExceptione){ // TODO(developer) - handle error appropriately GoogleJsonErrorerror=e.getDetails(); if(error.getCode()==403){ System.err.println("Unable to enable auto reply: "+e.getDetails()); }else{ throwe; } } returnnull; } }
Python
fromdatetimeimport datetime, timedelta importgoogle.auth fromgoogleapiclient.discoveryimport build fromgoogleapiclient.errorsimport HttpError fromnumpyimport long defenable_auto_reply(): """Enable auto reply. Returns:Draft object, including reply message and response meta data. Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for the application. """ creds, _ = google.auth.default() try: # create gmail api client service = build("gmail", "v1", credentials=creds) epoch = datetime.utcfromtimestamp(0) now = datetime.now() start_time = (now - epoch).total_seconds() * 1000 end_time = (now + timedelta(days=7) - epoch).total_seconds() * 1000 vacation_settings = { "enableAutoReply": True, "responseBodyHtml": ( "I am on vacation and will reply when I am " "back in the office. Thanks!" ), "restrictToDomain": True, "startTime": long(start_time), "endTime": long(end_time), } # pylint: disable=E1101 response = ( service.users() .settings() .updateVacation(userId="me", body=vacation_settings) .execute() ) print(f"Enabled AutoReply with message: {response.get('responseBodyHtml')}") except HttpError as error: print(f"An error occurred: {error}") response = None return response if __name__ == "__main__": enable_auto_reply()
To disable automatic reply, call the
settings.updateVacation
method and set the
enableAutoReply
field on the VacationSettings object to false. If you set an endTime
value, automatic reply is disabled once the specified time has passed.