Skip to content

Commit 05736e8

Browse files
RajeshGovosanjuktaghosh7Manvendra-P-Singh
authored
Gmail unit testcase (googleworkspace#234)
* git-on-borg files of gmail-api-snippets * Update build.gradle test12 * Update build.gradle * Gmail-snippets * Gmail unit testcase * Gmail unit testcase * Gmail snippet * Gmail snippet * Gmail snippet * Gmail snippet Co-authored-by: sanjuktaghosh7 <sanjuktaghosh@google.com> Co-authored-by: Manvendra-P-Singh <singhmanvendra@google.com>
1 parent bb59d2e commit 05736e8

34 files changed

Lines changed: 1079 additions & 742 deletions

gmail/snippets/build.gradle

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,10 @@ repositories {
55
}
66

77
dependencies {
8-
implementation 'com.google.api-client:google-api-client:1.33.0'
9-
implementation 'com.google.auth:google-auth-library-oauth2-http:1.3.0'
10-
implementation 'com.google.apis:google-api-services-gmail:v1-rev20211108-1.32.1'
11-
implementation 'com.google.code.gson:gson:2.4'
12-
implementation 'javax.mail:mail:1.4'
13-
implementation 'org.apache.commons:commons-csv:1.1'
8+
implementation 'com.google.auth:google-auth-library-oauth2-http:1.6.0'
9+
implementation 'com.google.apis:google-api-services-gmail:v1-rev20220404-1.32.1'
10+
implementation 'javax.mail:mail:1.4.7'
11+
implementation 'org.apache.commons:commons-csv:1.9.0'
1412
testImplementation 'junit:junit:4.13.2'
15-
testImplementation 'org.hamcrest:hamcrest-all:1.3'
16-
//testImplementation 'org.mockito:mockito-core:4.2.0'
17-
testImplementation 'org.mockito:mockito-inline:4.3.1'
13+
testImplementation 'org.mockito:mockito-inline:4.5.1'
1814
}

gmail/snippets/src/main/java/CreateDraft.java

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515

1616
// [START gmail_create_draft]
17+
import com.google.api.client.googleapis.json.GoogleJsonError;
1718
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
1819
import com.google.api.client.http.HttpRequestInitializer;
1920
import com.google.api.client.http.javanet.NetHttpTransport;
@@ -32,7 +33,6 @@
3233
import javax.mail.internet.MimeMessage;
3334
import java.io.ByteArrayOutputStream;
3435
import java.io.IOException;
35-
import java.util.Collections;
3636
import java.util.Properties;
3737

3838
/* Class to demonstrate the use of Gmail Create Draft API */
@@ -42,16 +42,16 @@ public class CreateDraft {
4242
*
4343
* @param fromEmailAddress - Email address to appear in the from: header
4444
* @param toEmailAddress - Email address of the recipient
45-
* @return the created draft
46-
* @throws MessagingException
47-
* @throws IOException
45+
* @return the created draft, {@code null} otherwise.
46+
* @throws MessagingException - if a wrongly formatted address is encountered.
47+
* @throws IOException - if service account credentials file not found.
4848
*/
4949
public static Draft createDraftMessage(String fromEmailAddress,
5050
String toEmailAddress)
5151
throws MessagingException, IOException {
52-
// Load pre-authorized user credentials from the environment.
53-
// TODO(developer) - See https://developers.google.com/identity for
54-
// guides on implementing OAuth2 for your application.
52+
/* Load pre-authorized user credentials from the environment.
53+
TODO(developer) - See https://developers.google.com/identity for
54+
guides on implementing OAuth2 for your application.*/
5555
GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
5656
.createScoped(GmailScopes.GMAIL_COMPOSE);
5757
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);
@@ -95,9 +95,14 @@ public static Draft createDraftMessage(String fromEmailAddress,
9595
return draft;
9696
} catch (GoogleJsonResponseException e) {
9797
// TODO(developer) - handle error appropriately
98-
System.err.println("Unable to create draft: " + e.getDetails());
99-
throw e;
98+
GoogleJsonError error = e.getDetails();
99+
if (error.getCode() == 403) {
100+
System.err.println("Unable to create draft: " + e.getMessage());
101+
} else {
102+
throw e;
103+
}
100104
}
105+
return null;
101106
}
102107
}
103108
// [END gmail_create_draft]

gmail/snippets/src/main/java/CreateDraftWithAttachment.java

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515

1616
// [START gmail_create_draft_with_attachment]
17+
import com.google.api.client.googleapis.json.GoogleJsonError;
1718
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
1819
import com.google.api.client.http.HttpRequestInitializer;
1920
import com.google.api.client.http.javanet.NetHttpTransport;
@@ -45,24 +46,24 @@
4546
/* Class to demonstrate the use of Gmail Create Draft with attachment API */
4647
public class CreateDraftWithAttachment {
4748
/**
48-
* Create a draft email.
49+
* Create a draft email with attachment.
4950
*
5051
* @param fromEmailAddress - Email address to appear in the from: header.
5152
* @param toEmailAddress - Email address of the recipient.
5253
* @param file - Path to the file to be attached.
53-
* @return the created draft
54+
* @return the created draft, {@code null} otherwise.
5455
* @throws MessagingException - if a wrongly formatted address is encountered.
5556
* @throws IOException - if service account credentials file not found.
5657
*/
5758
public static Draft createDraftMessageWithAttachment(String fromEmailAddress,
5859
String toEmailAddress,
5960
File file)
6061
throws MessagingException, IOException {
61-
// Load pre-authorized user credentials from the environment.
62-
// TODO(developer) - See https://developers.google.com/identity for
63-
// guides on implementing OAuth2 for your application.
64-
GoogleCredentials credentials = GoogleCredentials.getApplicationDefault().createScoped(
65-
GmailScopes.GMAIL_COMPOSE);
62+
/* Load pre-authorized user credentials from the environment.
63+
TODO(developer) - See https://developers.google.com/identity for
64+
guides on implementing OAuth2 for your application.*/
65+
GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
66+
.createScoped(GmailScopes.GMAIL_COMPOSE);
6667
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);
6768

6869
// Create the gmail API client
@@ -114,9 +115,14 @@ public static Draft createDraftMessageWithAttachment(String fromEmailAddress,
114115
return draft;
115116
} catch (GoogleJsonResponseException e) {
116117
// TODO(developer) - handle error appropriately
117-
System.err.println("Unable to create draft: " + e.getDetails());
118-
throw e;
118+
GoogleJsonError error = e.getDetails();
119+
if (error.getCode() == 403){
120+
System.err.println("Unable to create draft: " + e.getDetails());
121+
} else {
122+
throw e;
123+
}
119124
}
125+
return null;
120126
}
121127
}
122128
// [END gmail_create_draft_with_attachment]
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
// Copyright 2021 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// https://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
// [START gmail_create_email]
16+
import javax.mail.MessagingException;
17+
import javax.mail.Session;
18+
import javax.mail.internet.InternetAddress;
19+
import javax.mail.internet.MimeMessage;
20+
import java.util.Properties;
21+
22+
/* Class to demonstrate the use of Gmail Create Email API */
23+
public class CreateEmail {
24+
25+
/**
26+
* Create a MimeMessage using the parameters provided.
27+
*
28+
* @param toEmailAddress email address of the receiver
29+
* @param fromEmailAddress email address of the sender, the mailbox account
30+
* @param subject subject of the email
31+
* @param bodyText body text of the email
32+
* @return the MimeMessage to be used to send email
33+
* @throws MessagingException - if a wrongly formatted address is encountered.
34+
*/
35+
public static MimeMessage createEmail(String toEmailAddress,
36+
String fromEmailAddress,
37+
String subject,
38+
String bodyText)
39+
throws MessagingException {
40+
Properties props = new Properties();
41+
Session session = Session.getDefaultInstance(props, null);
42+
43+
MimeMessage email = new MimeMessage(session);
44+
45+
email.setFrom(new InternetAddress(fromEmailAddress));
46+
email.addRecipient(javax.mail.Message.RecipientType.TO,
47+
new InternetAddress(toEmailAddress));
48+
email.setSubject(subject);
49+
email.setText(bodyText);
50+
return email;
51+
}
52+
}
53+
// [END gmail_create_email]

gmail/snippets/src/main/java/CreateFilter.java

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515

1616
// [START gmail_create_filter]
17+
import com.google.api.client.googleapis.json.GoogleJsonError;
1718
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
1819
import com.google.api.client.http.HttpRequestInitializer;
1920
import 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]
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// Copyright 2022 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// https://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
// [START gmail_create_message]
16+
import com.google.api.services.gmail.model.Message;
17+
import org.apache.commons.codec.binary.Base64;
18+
import javax.mail.MessagingException;
19+
import javax.mail.internet.MimeMessage;
20+
import java.io.ByteArrayOutputStream;
21+
import java.io.IOException;
22+
23+
/* Class to demonstrate the use of Gmail Create Message API */
24+
public class CreateMessage {
25+
26+
/**
27+
* Create a message from an email.
28+
*
29+
* @param emailContent Email to be set to raw of message
30+
* @return a message containing a base64url encoded email
31+
* @throws IOException - if service account credentials file not found.
32+
* @throws MessagingException - if a wrongly formatted address is encountered.
33+
*/
34+
public static Message createMessageWithEmail(MimeMessage emailContent)
35+
throws MessagingException, IOException {
36+
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
37+
emailContent.writeTo(buffer);
38+
byte[] bytes = buffer.toByteArray();
39+
String encodedEmail = Base64.encodeBase64URLSafeString(bytes);
40+
Message message = new Message();
41+
message.setRaw(encodedEmail);
42+
return message;
43+
}
44+
}
45+
// [END gmail_create_message]

gmail/snippets/src/main/java/EnableAutoReply.java

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515

1616
// [START gmail_enable_auto_reply]
17+
import com.google.api.client.googleapis.json.GoogleJsonError;
1718
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
1819
import com.google.api.client.http.HttpRequestInitializer;
1920
import com.google.api.client.http.javanet.NetHttpTransport;
@@ -38,15 +39,11 @@ public class EnableAutoReply {
3839
* @throws IOException - if service account credentials file not found.
3940
*/
4041
public static VacationSettings autoReply() throws IOException{
41-
// TODO(developer) - Replace with your email address.
42-
String userEmail = "ci-test01@workspacesamples.dev";
43-
4442
/* Load pre-authorized user credentials from the environment.
45-
TODO(developer) - See https://developers.google.com/identity for
46-
guides on implementing OAuth2 for your application. */
43+
TODO(developer) - See https://developers.google.com/identity for
44+
guides on implementing OAuth2 for your application. */
4745
GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
48-
.createScoped(Collections.singleton(GmailScopes.GMAIL_SETTINGS_BASIC))
49-
.createDelegated(userEmail);
46+
.createScoped(GmailScopes.GMAIL_SETTINGS_BASIC);
5047
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);
5148

5249
// Create the gmail API client
@@ -74,9 +71,14 @@ public static VacationSettings autoReply() throws IOException{
7471
return response;
7572
} catch (GoogleJsonResponseException e) {
7673
// TODO(developer) - handle error appropriately
77-
System.err.println("Unable to enable auto reply: " + e.getDetails());
78-
throw e;
74+
GoogleJsonError error = e.getDetails();
75+
if (error.getCode() == 403) {
76+
System.err.println("Unable to enable auto reply: " + e.getDetails());
77+
} else {
78+
throw e;
79+
}
7980
}
81+
return null;
8082
}
8183
}
8284
// [END gmail_enable_auto_reply]

gmail/snippets/src/main/java/EnableForwarding.java

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515

1616
// [START gmail_enable_forwarding]
17+
import com.google.api.client.googleapis.json.GoogleJsonError;
1718
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
1819
import com.google.api.client.http.HttpRequestInitializer;
1920
import com.google.api.client.http.javanet.NetHttpTransport;
@@ -34,18 +35,14 @@ public class EnableForwarding {
3435
*
3536
* @param forwardingEmail - Email address of the recipient whose email will be forwarded.
3637
* @return forwarding id and metadata, {@code null} otherwise.
37-
* @throws IOException if service account credentials file not found.
38+
* @throws IOException - if service account credentials file not found.
3839
*/
3940
public static AutoForwarding enableAutoForwarding(String forwardingEmail) throws IOException{
40-
// TODO(developer) - Replace with your email address.
41-
String userEmail = "ci-test01@workspacesamples.dev";
42-
4341
/* Load pre-authorized user credentials from the environment.
4442
TODO(developer) - See https://developers.google.com/identity for
4543
guides on implementing OAuth2 for your application. */
4644
GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
47-
.createScoped(GmailScopes.GMAIL_SETTINGS_SHARING)
48-
.createDelegated(userEmail);
45+
.createScoped(GmailScopes.GMAIL_SETTINGS_SHARING);
4946
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);
5047

5148
// Create the gmail API client
@@ -72,8 +69,12 @@ public static AutoForwarding enableAutoForwarding(String forwardingEmail) throws
7269
}
7370
} catch (GoogleJsonResponseException e) {
7471
// TODO(developer) - handle error appropriately
75-
System.err.println("Unable to enable forwarding : " + e.getDetails());
76-
throw e;
72+
GoogleJsonError error = e.getDetails();
73+
if (error.getCode() == 403) {
74+
System.err.println("Unable to enable forwarding: " + e.getDetails());
75+
} else {
76+
throw e;
77+
}
7778
}
7879
return null;
7980
}

0 commit comments

Comments
 (0)