1414
1515
1616// [START gmail_create_filter]
17+ import com .google .api .client .googleapis .json .GoogleJsonError ;
1718import com .google .api .client .googleapis .json .GoogleJsonResponseException ;
1819import com .google .api .client .http .HttpRequestInitializer ;
1920import com .google .api .client .http .javanet .NetHttpTransport ;
@@ -33,20 +34,17 @@ public class CreateFilter {
3334 /**
3435 * Create a new filter.
3536 *
36- * @param realLabelId - ID of the user label to add
37- * @return the created filter id
37+ * @param labelId - ID of the user label to add
38+ * @return the created filter id, {@code null} otherwise.
3839 * @throws IOException - if service account credentials file not found.
3940 */
40- public static String createNewFilter (String realLabelId ) throws IOException {
41- // TODO(developer) - Replace with your email address.
42- String userEmail = "ci-test01@workspacesamples.dev" ;
43-
41+ public static String createNewFilter (String labelId ) throws IOException {
4442 /* Load pre-authorized user credentials from the environment.
4543 TODO(developer) - See https://developers.google.com/identity for
4644 guides on implementing OAuth2 for your application. */
4745 GoogleCredentials credentials = GoogleCredentials .getApplicationDefault ()
48- .createScoped (GmailScopes .GMAIL_SETTINGS_BASIC , GmailScopes . GMAIL_LABELS )
49- . createDelegated ( userEmail );
46+ .createScoped (GmailScopes .GMAIL_SETTINGS_BASIC ,
47+ GmailScopes . GMAIL_LABELS );
5048 HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter (credentials );
5149
5250 // Create the gmail API client
@@ -56,11 +54,6 @@ public static String createNewFilter(String realLabelId) throws IOException {
5654 .setApplicationName ("Gmail samples" )
5755 .build ();
5856
59- String labelId = "Label_14" ; // ID of the user label to add
60- // [START_EXCLUDE silent]
61- labelId = realLabelId ;
62- // [END_EXCLUDE]
63-
6457 try {
6558 // Filter the mail from sender and archive them(skip the inbox)
6659 Filter filter = new Filter ()
@@ -76,9 +69,14 @@ public static String createNewFilter(String realLabelId) throws IOException {
7669 return result .getId ();
7770 } catch (GoogleJsonResponseException e ) {
7871 // TODO(developer) - handle error appropriately
79- System .err .println ("Unable to create filter: " + e .getDetails ());
80- throw e ;
72+ GoogleJsonError error = e .getDetails ();
73+ if (error .getCode () == 403 ) {
74+ System .err .println ("Unable to create filter: " + e .getDetails ());
75+ } else {
76+ throw e ;
77+ }
8178 }
79+ return null ;
8280 }
8381}
8482// [END gmail_create_filter]
0 commit comments