Skip to content

Commit 7e5ec71

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

4 files changed

Lines changed: 338 additions & 0 deletions

File tree

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
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+
16+
// [START gmail_insert_cert_from_csv]
17+
import com.google.api.services.gmail.model.SmimeInfo;
18+
import org.apache.commons.csv.CSVFormat;
19+
import org.apache.commons.csv.CSVParser;
20+
import org.apache.commons.csv.CSVRecord;
21+
22+
import java.io.File;
23+
24+
/* Class to demonstrate the use of Gmail Insert Certificate from CSV File */
25+
public class InsertCertFromCsv {
26+
/**
27+
* Upload S/MIME certificates based on the contents of a CSV file.
28+
*
29+
* <p>Each row of the CSV file should contain a user ID, path to the certificate, and the
30+
* certificate password.
31+
*
32+
* @param csvFilename Name of the CSV file.
33+
*/
34+
public static void insertCertFromCsv(String csvFilename) {
35+
try {
36+
File csvFile = new File(csvFilename);
37+
CSVParser parser =
38+
CSVParser.parse(csvFile, java.nio.charset.StandardCharsets.UTF_8, CSVFormat.DEFAULT);
39+
for (CSVRecord record : parser) {
40+
String userId = record.get(0);
41+
String certFilename = record.get(1);
42+
String certPassword = record.get(2);
43+
SmimeInfo smimeInfo = CreateSmimeInfo.createSmimeInfo(certFilename,
44+
certPassword);
45+
if (smimeInfo != null) {
46+
InsertSmimeInfo.insertSmimeInfo(certFilename,
47+
certPassword,
48+
userId,
49+
userId);
50+
} else {
51+
System.err.printf("Unable to read certificate file for userId: %s\n", userId);
52+
}
53+
}
54+
} catch (Exception e) {
55+
System.err.printf("An error occured while reading the CSV file: %s", e);
56+
}
57+
}
58+
}
59+
// [END gmail_insert_cert_from_csv]
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
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+
16+
// [START gmail_insert_smime_info]
17+
import com.google.api.client.http.HttpRequestInitializer;
18+
import com.google.api.client.http.javanet.NetHttpTransport;
19+
import com.google.api.client.json.gson.GsonFactory;
20+
import com.google.api.services.gmail.Gmail;
21+
import com.google.api.services.gmail.GmailScopes;
22+
import com.google.api.services.gmail.model.SmimeInfo;
23+
import com.google.auth.http.HttpCredentialsAdapter;
24+
import com.google.auth.oauth2.GoogleCredentials;
25+
26+
import java.io.IOException;
27+
import java.util.Collections;
28+
29+
/* Class to demonstrate the use of Gmail Insert Smime Certificate API*/
30+
public class InsertSmimeInfo {
31+
/**
32+
* Upload an S/MIME certificate for the user.
33+
*
34+
* @param filename Name of the file containing the S/MIME certificate.
35+
* @param password Password for the certificate file, or null if the file
36+
* is not password-protected.
37+
* @param userId User's email address.
38+
* @param sendAsEmail The "send as" email address, or null if it should be the same as userId.
39+
* @return An SmimeInfo object with details about the uploaded certificate.
40+
*/
41+
public static SmimeInfo insertSmimeInfo(String filename,
42+
String password,
43+
String userId,
44+
String sendAsEmail)
45+
throws IOException {
46+
/* Load pre-authorized user credentials from the environment.
47+
TODO(developer) - See https://developers.google.com/identity for
48+
guides on implementing OAuth2 for your application. */
49+
GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
50+
.createScoped(Collections.singletonList(GmailScopes.GMAIL_SETTINGS_SHARING));
51+
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
52+
credentials);
53+
54+
// Create the gmail API client
55+
Gmail service = new Gmail.Builder(new NetHttpTransport(),
56+
GsonFactory.getDefaultInstance(),
57+
requestInitializer)
58+
.setApplicationName("Gmail samples")
59+
.build();
60+
61+
if (sendAsEmail == null) {
62+
sendAsEmail = userId;
63+
}
64+
65+
try {
66+
SmimeInfo smimeInfo = CreateSmimeInfo.createSmimeInfo(filename, password);
67+
SmimeInfo results = service.users().settings().sendAs().smimeInfo()
68+
.insert(userId, sendAsEmail, smimeInfo)
69+
.execute();
70+
System.out.printf("Inserted certificate, id: %s\n", results.getId());
71+
return results;
72+
} catch (IOException e) {
73+
System.err.printf("An error occured: %s", e);
74+
}
75+
76+
return null;
77+
}
78+
}
79+
// [END gmail_insert_smime_info]
Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
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+
16+
// [START gmail_update_smime_certs]
17+
import com.google.api.client.http.HttpRequestInitializer;
18+
import com.google.api.client.http.javanet.NetHttpTransport;
19+
import com.google.api.client.json.gson.GsonFactory;
20+
import com.google.api.services.gmail.Gmail;
21+
import com.google.api.services.gmail.GmailScopes;
22+
import com.google.api.services.gmail.model.ListSmimeInfoResponse;
23+
import com.google.api.services.gmail.model.SmimeInfo;
24+
import com.google.auth.http.HttpCredentialsAdapter;
25+
import com.google.auth.oauth2.GoogleCredentials;
26+
27+
import java.io.IOException;
28+
import java.time.Instant;
29+
import java.time.LocalDateTime;
30+
import java.time.ZoneId;
31+
import java.util.Collections;
32+
33+
/* Class to demonstrate the use of Gmail Update Smime Certificate API*/
34+
public class UpdateSmimeCerts {
35+
/**
36+
* Update S/MIME certificates for the user.
37+
*
38+
* <p>First performs a lookup of all certificates for a user. If there are no certificates, or
39+
* they all expire before the specified date/time, uploads the certificate in the specified file.
40+
* If the default certificate is expired or there was no default set, chooses the certificate with
41+
* the expiration furthest into the future and sets it as default.
42+
*
43+
* @param userId User's email address.
44+
* @param sendAsEmail The "send as" email address, or None if it should be the same as user_id.
45+
* @param certFilename Name of the file containing the S/MIME certificate.
46+
* @param certPassword Password for the certificate file, or None if the file is not
47+
* password-protected.
48+
* @param expireTime DateTime object against which the certificate expiration is compared. If
49+
* None, uses the current time. @ returns: The ID of the default certificate.
50+
* @return The ID of the default certifcate.
51+
*/
52+
public static String updateSmimeCerts(String userId,
53+
String sendAsEmail,
54+
String certFilename,
55+
String certPassword,
56+
LocalDateTime expireTime)
57+
throws IOException {
58+
/* Load pre-authorized user credentials from the environment.
59+
TODO(developer) - See https://developers.google.com/identity for
60+
guides on implementing OAuth2 for your application. */
61+
GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
62+
.createScoped(Collections.singletonList(GmailScopes.GMAIL_SETTINGS_SHARING));
63+
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
64+
credentials);
65+
66+
// Create the gmail API client
67+
Gmail service = new Gmail.Builder(new NetHttpTransport(),
68+
GsonFactory.getDefaultInstance(),
69+
requestInitializer)
70+
.setApplicationName("Gmail samples")
71+
.build();
72+
73+
if (sendAsEmail == null) {
74+
sendAsEmail = userId;
75+
}
76+
77+
ListSmimeInfoResponse listResults;
78+
try {
79+
listResults = service.users().settings().sendAs().smimeInfo().list(userId, sendAsEmail).execute();
80+
} catch (IOException e) {
81+
System.err.printf("An error occurred during list: %s\n", e);
82+
return null;
83+
}
84+
85+
String defaultCertId = null;
86+
String bestCertId = null;
87+
LocalDateTime bestCertExpire = LocalDateTime.MIN;
88+
89+
if (expireTime == null) {
90+
expireTime = LocalDateTime.now();
91+
}
92+
if (listResults != null && listResults.getSmimeInfo() != null) {
93+
for (SmimeInfo smimeInfo : listResults.getSmimeInfo()) {
94+
String certId = smimeInfo.getId();
95+
boolean isDefaultCert = smimeInfo.getIsDefault();
96+
if (isDefaultCert) {
97+
defaultCertId = certId;
98+
}
99+
LocalDateTime exp =
100+
LocalDateTime.ofInstant(
101+
Instant.ofEpochMilli(smimeInfo.getExpiration()), ZoneId.systemDefault());
102+
if (exp.isAfter(expireTime)) {
103+
if (exp.isAfter(bestCertExpire)) {
104+
bestCertId = certId;
105+
bestCertExpire = exp;
106+
}
107+
} else {
108+
if (isDefaultCert) {
109+
defaultCertId = null;
110+
}
111+
}
112+
}
113+
}
114+
if (defaultCertId == null) {
115+
String defaultId = bestCertId;
116+
if (defaultId == null && certFilename != null) {
117+
SmimeInfo insertResults = InsertSmimeInfo.insertSmimeInfo(certFilename,
118+
certPassword,
119+
userId,
120+
sendAsEmail);
121+
if (insertResults != null) {
122+
defaultId = insertResults.getId();
123+
}
124+
}
125+
126+
if (defaultId != null) {
127+
try {
128+
service.users().settings().sendAs().smimeInfo().setDefault(userId, sendAsEmail, defaultId).execute();
129+
return defaultId;
130+
} catch (IOException e) {
131+
System.err.printf("An error occured during setDefault: %s", e);
132+
}
133+
}
134+
} else {
135+
return defaultCertId;
136+
}
137+
138+
return null;
139+
}
140+
}
141+
// [END gmail_update_smime_certs]
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
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+
16+
// [START gmail_update_smime_from_csv]
17+
import org.apache.commons.csv.CSVFormat;
18+
import org.apache.commons.csv.CSVParser;
19+
import org.apache.commons.csv.CSVRecord;
20+
21+
import java.io.File;
22+
import java.time.LocalDateTime;
23+
24+
/* Class to demonstrate the use of Gmail Update Certificate from CSV File */
25+
public class UpdateSmimeFromCsv {
26+
/**
27+
* Update S/MIME certificates based on the contents of a CSV file.
28+
*
29+
* <p>Each row of the CSV file should contain a user ID, path to the certificate, and the
30+
* certificate password.
31+
*
32+
* @param csvFilename Name of the CSV file.
33+
* @param expireTime DateTime object against which the certificate expiration is compared. If
34+
* None, uses the current time.
35+
*/
36+
public static void updateSmimeFromCsv(String csvFilename, LocalDateTime expireTime) {
37+
try {
38+
File csvFile = new File(csvFilename);
39+
CSVParser parser =
40+
CSVParser.parse(
41+
csvFile,
42+
java.nio.charset.StandardCharsets.UTF_8,
43+
CSVFormat.DEFAULT.withHeader().withSkipHeaderRecord());
44+
for (CSVRecord record : parser) {
45+
String userId = record.get(0);
46+
String certFilename = record.get(1);
47+
String certPassword = record.get(2);
48+
UpdateSmimeCerts.updateSmimeCerts(userId,
49+
userId,
50+
certFilename,
51+
certPassword,
52+
expireTime);
53+
}
54+
} catch (Exception e) {
55+
System.err.printf("An error occured while reading the CSV file: %s", e);
56+
}
57+
}
58+
}
59+
// [END gmail_update_smime_from_csv]

0 commit comments

Comments
 (0)