Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
ef8d99f
git-on-borg files of gmail-api-snippets
sanjuktaghosh7 Jan 14, 2022
f8d22fe
Merge pull request #2 from sanjuktaghosh7/delRel
RajeshGovo Jan 14, 2022
0c9e47a
Merge pull request #3 from RajeshGogo/delRel
RajeshGovo Jan 14, 2022
494c98e
Merge branch 'googleworkspace:master' into master
sanjuktaghosh7 Jan 19, 2022
cc07ac4
Update build.gradle
Manvendra-P-Singh Jan 19, 2022
dd55a6a
Merge pull request #8 from RajeshGogo/Manvendra-P-Singh-patch-1
RajeshGovo Jan 19, 2022
de85a1a
Merge pull request #9 from RajeshGogo/test1
RajeshGovo Jan 19, 2022
352491b
Update build.gradle
RajeshGovo Jan 19, 2022
5b70dce
Merge branch 'googleworkspace:master' into master
RajeshGovo Jan 20, 2022
740f231
Merge branch 'googleworkspace:master' into master
RajeshGovo Jan 25, 2022
60813f8
Merge branch 'googleworkspace:master' into master
Manvendra-P-Singh Feb 1, 2022
5e1358d
Merge branch 'googleworkspace:master' into master
RajeshGovo Feb 3, 2022
ed9ffec
Merge branch 'googleworkspace:master' into master
sanjuktaghosh7 Feb 8, 2022
ddca4b4
Merge branch 'googleworkspace:master' into master
RajeshGovo Feb 9, 2022
460e238
Merge branch 'googleworkspace:master' into master
RajeshGovo Feb 16, 2022
64950d1
Merge branch 'googleworkspace:master' into master
Manvendra-P-Singh Feb 25, 2022
a48179e
Merge branch 'googleworkspace:master' into master
Manvendra-P-Singh Mar 3, 2022
d58a5f8
Merge branch 'googleworkspace:master' into master
Manvendra-P-Singh Mar 8, 2022
3c749b1
Merge branch 'googleworkspace:master' into master
sanjuktaghosh7 Mar 8, 2022
6b6cef8
gmail snippets
sanjuktaghosh7 Mar 16, 2022
e9a26e2
Merge remote-tracking branch 'origin/gmail-snippet' into gmail-snippet
sanjuktaghosh7 Mar 16, 2022
77e052f
Merge branch 'googleworkspace:master' into gmail-snippet
sanjuktaghosh7 Mar 16, 2022
a4f7ff5
Merge pull request #78 from sanjuktaghosh7/gmail-snippet
RajeshGovo Mar 16, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions gmail/snippets/src/main/java/InsertCertFromCsv.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.


// [START gmail_insert_cert_from_csv]
import com.google.api.services.gmail.model.SmimeInfo;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;

import java.io.File;

/* Class to demonstrate the use of Gmail Insert Certificate from CSV File */
public class InsertCertFromCsv {
/**
* Upload S/MIME certificates based on the contents of a CSV file.
*
* <p>Each row of the CSV file should contain a user ID, path to the certificate, and the
* certificate password.
*
* @param csvFilename Name of the CSV file.
*/
public static void insertCertFromCsv(String csvFilename) {
try {
File csvFile = new File(csvFilename);
CSVParser parser =
CSVParser.parse(csvFile, java.nio.charset.StandardCharsets.UTF_8, CSVFormat.DEFAULT);
for (CSVRecord record : parser) {
String userId = record.get(0);
String certFilename = record.get(1);
String certPassword = record.get(2);
SmimeInfo smimeInfo = CreateSmimeInfo.createSmimeInfo(certFilename,
certPassword);
if (smimeInfo != null) {
InsertSmimeInfo.insertSmimeInfo(certFilename,
certPassword,
userId,
userId);
} else {
System.err.printf("Unable to read certificate file for userId: %s\n", userId);
}
}
} catch (Exception e) {
System.err.printf("An error occured while reading the CSV file: %s", e);
}
}
}
// [END gmail_insert_cert_from_csv]
79 changes: 79 additions & 0 deletions gmail/snippets/src/main/java/InsertSmimeInfo.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.


// [START gmail_insert_smime_info]
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.gmail.model.SmimeInfo;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;

import java.io.IOException;
import java.util.Collections;

/* Class to demonstrate the use of Gmail Insert Smime Certificate API*/
public class InsertSmimeInfo {
/**
* Upload an S/MIME certificate for the user.
*
* @param filename Name of the file containing the S/MIME certificate.
* @param password Password for the certificate file, or null if the file
* is not password-protected.
* @param userId User's email address.
* @param sendAsEmail The "send as" email address, or null if it should be the same as userId.
* @return An SmimeInfo object with details about the uploaded certificate.
*/
public static SmimeInfo insertSmimeInfo(String filename,
String password,
String userId,
String sendAsEmail)
throws IOException {
/* Load pre-authorized user credentials from the environment.
TODO(developer) - See https://developers.google.com/identity for
guides on implementing OAuth2 for your application. */
GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
.createScoped(Collections.singletonList(GmailScopes.GMAIL_SETTINGS_SHARING));
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
credentials);

// Create the gmail API client
Gmail service = new Gmail.Builder(new NetHttpTransport(),
GsonFactory.getDefaultInstance(),
requestInitializer)
.setApplicationName("Gmail samples")
.build();

if (sendAsEmail == null) {
sendAsEmail = userId;
}

try {
SmimeInfo smimeInfo = CreateSmimeInfo.createSmimeInfo(filename, password);
SmimeInfo results = service.users().settings().sendAs().smimeInfo()
.insert(userId, sendAsEmail, smimeInfo)
.execute();
System.out.printf("Inserted certificate, id: %s\n", results.getId());
return results;
} catch (IOException e) {
System.err.printf("An error occured: %s", e);
}

return null;
}
}
// [END gmail_insert_smime_info]
141 changes: 141 additions & 0 deletions gmail/snippets/src/main/java/UpdateSmimeCerts.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.


// [START gmail_update_smime_certs]
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.gmail.model.ListSmimeInfoResponse;
import com.google.api.services.gmail.model.SmimeInfo;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Collections;

/* Class to demonstrate the use of Gmail Update Smime Certificate API*/
public class UpdateSmimeCerts {
/**
* Update S/MIME certificates for the user.
*
* <p>First performs a lookup of all certificates for a user. If there are no certificates, or
* they all expire before the specified date/time, uploads the certificate in the specified file.
* If the default certificate is expired or there was no default set, chooses the certificate with
* the expiration furthest into the future and sets it as default.
*
* @param userId User's email address.
* @param sendAsEmail The "send as" email address, or None if it should be the same as user_id.
* @param certFilename Name of the file containing the S/MIME certificate.
* @param certPassword Password for the certificate file, or None if the file is not
* password-protected.
* @param expireTime DateTime object against which the certificate expiration is compared. If
* None, uses the current time. @ returns: The ID of the default certificate.
* @return The ID of the default certifcate.
*/
public static String updateSmimeCerts(String userId,
String sendAsEmail,
String certFilename,
String certPassword,
LocalDateTime expireTime)
throws IOException {
/* Load pre-authorized user credentials from the environment.
TODO(developer) - See https://developers.google.com/identity for
guides on implementing OAuth2 for your application. */
GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
.createScoped(Collections.singletonList(GmailScopes.GMAIL_SETTINGS_SHARING));
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
credentials);

// Create the gmail API client
Gmail service = new Gmail.Builder(new NetHttpTransport(),
GsonFactory.getDefaultInstance(),
requestInitializer)
.setApplicationName("Gmail samples")
.build();

if (sendAsEmail == null) {
sendAsEmail = userId;
}

ListSmimeInfoResponse listResults;
try {
listResults = service.users().settings().sendAs().smimeInfo().list(userId, sendAsEmail).execute();
} catch (IOException e) {
System.err.printf("An error occurred during list: %s\n", e);
return null;
}

String defaultCertId = null;
String bestCertId = null;
LocalDateTime bestCertExpire = LocalDateTime.MIN;

if (expireTime == null) {
expireTime = LocalDateTime.now();
}
if (listResults != null && listResults.getSmimeInfo() != null) {
for (SmimeInfo smimeInfo : listResults.getSmimeInfo()) {
String certId = smimeInfo.getId();
boolean isDefaultCert = smimeInfo.getIsDefault();
if (isDefaultCert) {
defaultCertId = certId;
}
LocalDateTime exp =
LocalDateTime.ofInstant(
Instant.ofEpochMilli(smimeInfo.getExpiration()), ZoneId.systemDefault());
if (exp.isAfter(expireTime)) {
if (exp.isAfter(bestCertExpire)) {
bestCertId = certId;
bestCertExpire = exp;
}
} else {
if (isDefaultCert) {
defaultCertId = null;
}
}
}
}
if (defaultCertId == null) {
String defaultId = bestCertId;
if (defaultId == null && certFilename != null) {
SmimeInfo insertResults = InsertSmimeInfo.insertSmimeInfo(certFilename,
certPassword,
userId,
sendAsEmail);
if (insertResults != null) {
defaultId = insertResults.getId();
}
}

if (defaultId != null) {
try {
service.users().settings().sendAs().smimeInfo().setDefault(userId, sendAsEmail, defaultId).execute();
return defaultId;
} catch (IOException e) {
System.err.printf("An error occured during setDefault: %s", e);
}
}
} else {
return defaultCertId;
}

return null;
}
}
// [END gmail_update_smime_certs]
59 changes: 59 additions & 0 deletions gmail/snippets/src/main/java/UpdateSmimeFromCsv.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.


// [START gmail_update_smime_from_csv]
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;

import java.io.File;
import java.time.LocalDateTime;

/* Class to demonstrate the use of Gmail Update Certificate from CSV File */
public class UpdateSmimeFromCsv {
/**
* Update S/MIME certificates based on the contents of a CSV file.
*
* <p>Each row of the CSV file should contain a user ID, path to the certificate, and the
* certificate password.
*
* @param csvFilename Name of the CSV file.
* @param expireTime DateTime object against which the certificate expiration is compared. If
* None, uses the current time.
*/
public static void updateSmimeFromCsv(String csvFilename, LocalDateTime expireTime) {
try {
File csvFile = new File(csvFilename);
CSVParser parser =
CSVParser.parse(
csvFile,
java.nio.charset.StandardCharsets.UTF_8,
CSVFormat.DEFAULT.withHeader().withSkipHeaderRecord());
for (CSVRecord record : parser) {
String userId = record.get(0);
String certFilename = record.get(1);
String certPassword = record.get(2);
UpdateSmimeCerts.updateSmimeCerts(userId,
userId,
certFilename,
certPassword,
expireTime);
}
} catch (Exception e) {
System.err.printf("An error occured while reading the CSV file: %s", e);
}
}
}
// [END gmail_update_smime_from_csv]