S/MIME सर्टिफ़िकेट मैनेज करना

Gmail S/MIME API, प्रोग्राम के हिसाब से अपने-आप होने वाली सुविधा का ऐक्सेस देता है, ताकि आप Google Workspace डोमेन के उपयोगकर्ताओं के लिए, S/MIME ईमेल सर्टिफ़िकेट मैनेज कर सकें.

एडमिन को डोमेन के लिए S/MIME चालू करना होगा, ताकि सर्टिफ़िकेट काम कर सकें.

S/MIME स्टैंडर्ड में सार्वजनिक कुंजी से डेटा को एन्क्रिप्ट (सुरक्षित) करने और MIME डेटा पर हस्ताक्षर करने की खास जानकारी मिलती है. किसी उपयोगकर्ता के खाते में S/MIME सर्टिफ़िकेट कॉन्फ़िगर करने से, Gmail उस सर्टिफ़िकेट का इस्तेमाल इन तरीकों से करता है:

  • Gmail, आउटगोइंग मेल पर हस्ताक्षर करने के लिए उपयोगकर्ता के प्रमाणपत्र और निजी कुंजी का इस्तेमाल करता है.
  • Gmail, उपयोगकर्ता की निजी कुंजी का इस्तेमाल करके, आने वाले ईमेल को डिक्रिप्ट करता है.
  • Gmail, आउटगोइंग मेल को एन्क्रिप्ट करने के लिए पाने वाले के प्रमाणपत्र और सार्वजनिक कुंजी का इस्तेमाल करता है.
  • Gmail, इनकमिंग मेल की पुष्टि करने के लिए भेजने वाले के प्रमाणपत्र और सार्वजनिक कुंजी का इस्तेमाल करता है.

आपके पास अलग-अलग S/MIME सर्टिफ़िकेट जनरेट करने और उन्हें एपीआई का इस्तेमाल करके अपलोड करने का विकल्प होता है. हर S/MIME सर्टिफ़िकेट, उपयोगकर्ता के ईमेल खाते के खास उपनाम के लिए होता है. उपनामों में प्राथमिक ईमेल पते के साथ-साथ कस्टम "इस रूप में भेजें" पते शामिल होते हैं. हर उपनाम के लिए, एक S/MIME सर्टिफ़िकेट को डिफ़ॉल्ट के तौर पर मार्क किया जाता है.

एपीआई ऐक्सेस को अनुमति देना

एपीआई ऐक्सेस करने के लिए, अनुमति देने के दो तरीके होते हैं:

  1. सेवा खाते का इस्तेमाल करने के लिए, आपको पूरे डोमेन पर अधिकार देने वाली संस्था या निकाय का ऐक्सेस होना चाहिए. इन शर्तों के बारे में ज़्यादा जानकारी के लिए, पुष्टि करने और अनुमति देने से जुड़ी खास जानकारी वाली शर्तें देखें. इस विकल्प को चालू करने के बारे में जानकारी पाने के लिए, पूरे डोमेन पर अधिकार देने वाली संस्था की मदद से सेवा खाता बनाना देखें
  2. स्टैंडर्ड OAuth2 फ़्लो का इस्तेमाल किया जा सकता है, जिसमें Oauth2 ऐक्सेस टोकन लेने के लिए असली उपयोगकर्ता की सहमति लेनी पड़ती है. ज़्यादा जानकारी के लिए, पुष्टि करने और अनुमति देने से जुड़ी खास जानकारी देखें इस विकल्प का इस्तेमाल करने के लिए, डोमेन एडमिन को डोमेन कंट्रोल पैनल में "S/MIME API असली उपयोगकर्ता का ऐक्सेस चालू है" चेकबॉक्स को चालू करना होगा.

ACL स्कोप

यह एपीआई उसी ACL स्कोप पर निर्भर करता है जिन पर Gmail sendAs तरीके का इस्तेमाल किया जाता है:

gmail.settings.basic
यह दायरा, मुख्य SendAs S/MIME को अपडेट करने के लिए ज़रूरी है.
gmail.settings.sharing
S/MIME से कस्टम अपडेट करने के लिए यह दायरा ज़रूरी है.

एपीआई का इस्तेमाल करना

users.settings.sendAs.smimeInfo संसाधन में ऐसे तरीके उपलब्ध हैं जिनका इस्तेमाल करके, S/MIME सर्टिफ़िकेट मैनेज किए जा सकते हैं. हर सर्टिफ़िकेट, किसी उपयोगकर्ता के लिए एक उपनाम से जुड़ा होता है.

S/MIME कुंजी अपलोड करें

किसी उपयोगकर्ता से जुड़े उपनाम के लिए एक नई S/MIME कुंजी अपलोड करने के लिए smimeInfo.insert() तरीके का इस्तेमाल करें. टारगेट उपनाम की पहचान करने के लिए, नीचे दिए गए पैरामीटर का इस्तेमाल करें:

userId
उपयोगकर्ता का ईमेल पता. फ़िलहाल, पुष्टि किए गए उपयोगकर्ता की जानकारी देने के लिए, खास वैल्यू me का इस्तेमाल किया जा सकता है.
sendAsEmail
वह उपनाम जिसके लिए कुंजी अपलोड की जा रही है. यह वह ईमेल पता है जो इस उपनाम का इस्तेमाल करके भेजे गए ईमेल के लिए, "भेजने वाला:" हेडर में दिखता है.

इस फ़ॉर्मैट के pkcs12 फ़ील्ड में S/MIME सर्टिफ़िकेट और निजी कुंजी मौजूद होनी चाहिए; अनुरोध में कोई दूसरा फ़ील्ड सेट नहीं किया जाना चाहिए. PKCS12 फ़ील्ड में उपयोगकर्ता S/MIME कुंजी और साइनिंग सर्टिफ़िकेट चेन, दोनों होने की उम्मीद होती है. एपीआई इस फ़ील्ड को स्वीकार करने से पहले, उस पर स्टैंडर्ड पुष्टि करता है और इनकी पुष्टि करता है:

  • विषय, दिए गए ईमेल पते से मेल खाता है.
  • समयसीमाएं मान्य हैं.
  • जारी करने वाली संस्था या निकाय (CA) हमारी भरोसेमंद सूची में शामिल है.
  • प्रमाणपत्र, Gmail की तकनीकी सीमाओं से मेल खाते हैं.

अगर कुंजी को एन्क्रिप्ट (सुरक्षित) किया गया है, तो पासवर्ड encryptedKeyPassword फ़ील्ड में होना चाहिए. कामयाब इंसर्शन() कॉल करने पर smimeInfo आईडी मिलेगा. इसका इस्तेमाल आने वाले समय में कुंजी का रेफ़रंस देने के लिए किया जा सकता है.

उपयोगकर्ता की S/MIME कुंजियों की सूची बनाएं

दिए गए उपनाम के लिए, किसी उपयोगकर्ता के लिए S/MIME कुंजियों की सूची दिखाने के लिए, smimeInfo.list() तरीके का इस्तेमाल करें. टारगेट उपनाम की पहचान करने के लिए, नीचे दिए गए पैरामीटर का इस्तेमाल करें:

userId
उपयोगकर्ता का ईमेल पता. फ़िलहाल, पुष्टि किए गए उपयोगकर्ता की जानकारी देने के लिए, खास वैल्यू me का इस्तेमाल किया जा सकता है.
sendAsEmail
वह उपनाम जिसके लिए कुंजियों की सूची बनानी है. यह वह ईमेल पता है जो इस उपनाम का इस्तेमाल करके भेजे गए ईमेल के लिए, "भेजने वाला:" हेडर में दिखता है.

किसी उपनाम के लिए S/MIME कुंजियां वापस पाएं

किसी उपयोगकर्ता को दिखाए जाने वाले खास उपनाम के लिए, खास S/MIME कुंजियां दिखाने के लिए smimeInfo.get() तरीके का इस्तेमाल करें. टारगेट उपनाम की पहचान करने के लिए, नीचे दिए गए पैरामीटर का इस्तेमाल करें:

userId
उपयोगकर्ता का ईमेल पता. फ़िलहाल, पुष्टि किए गए उपयोगकर्ता की जानकारी देने के लिए, खास वैल्यू me का इस्तेमाल किया जा सकता है.
sendAsEmail
वह उपनाम जिसके लिए आपको कुंजियां वापस लेनी हैं. यह वह ईमेल पता है जो इस उपनाम का इस्तेमाल करके भेजे गए ईमेल के लिए, "भेजने वाला:" हेडर में दिखता है.

S/MIME कुंजी मिटाना

किसी उपनाम से तय की गई S/MIME कुंजी मिटाने के लिए, smimeInfo.delete() तरीके का इस्तेमाल करें. टारगेट उपनाम की पहचान करने के लिए, नीचे दिए गए पैरामीटर का इस्तेमाल करें:

userId
उपयोगकर्ता का ईमेल पता. फ़िलहाल, पुष्टि किए गए उपयोगकर्ता की जानकारी देने के लिए, खास वैल्यू me का इस्तेमाल किया जा सकता है.
sendAsEmail
वह उपनाम जिसके लिए आपको कुंजियां वापस लेनी हैं. यह ईमेल पता, इस उपनाम का इस्तेमाल करके भेजे गए ईमेल के "भेजने वाला:" हेडर में दिखता है.
id
SmimeInfo के लिए नहीं बदला जा सकने वाला आईडी.

किसी उपनाम के लिए डिफ़ॉल्ट S/MIME कुंजी सेट करें

तय किए गए उपनाम के लिए, खास S/MIME कुंजी को डिफ़ॉल्ट के तौर पर मार्क करने के लिए, smimeInfo.setDefault() तरीके का इस्तेमाल करें. टारगेट उपनाम की पहचान करने के लिए, नीचे दिए गए पैरामीटर का इस्तेमाल करें:

userId
उपयोगकर्ता का ईमेल पता. फ़िलहाल, पुष्टि किए गए उपयोगकर्ता की जानकारी देने के लिए, खास वैल्यू me का इस्तेमाल किया जा सकता है.
sendAsEmail
वह उपनाम जिसके लिए आपको कुंजियां वापस लेनी हैं. यह ईमेल पता, इस उपनाम का इस्तेमाल करके भेजे गए ईमेल के "भेजने वाला:" हेडर में दिखता है.
id
SmimeInfo के लिए नहीं बदला जा सकने वाला आईडी.

नमूना कोड

नीचे दिए गए कोड सैंपल, एपीआई का इस्तेमाल करके कई उपयोगकर्ताओं वाले संगठन के लिए S/MIME सर्टिफ़िकेट को मैनेज करने के बारे में बताते हैं.

S/MIME सर्टिफ़िकेट के लिए, SmimeInfo संसाधन बनाना

नीचे दिए गए कोड सैंपल में बताया गया है कि फ़ाइल से सर्टिफ़िकेट पढ़ना, base64url स्ट्रिंग को कोड में बदलना, और उसे smimeInfo संसाधन के pkcs12 फ़ील्ड को असाइन करना:

Java

gmail/snippets/src/main/java/CreateSmimeInfo.java
import com.google.api.services.gmail.model.SmimeInfo;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;

/* Class to demonstrate the use of Gmail Create SmimeInfo API */
public class CreateSmimeInfo {
  /**
   * Create an SmimeInfo resource for a certificate from file.
   *
   * @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.
   * @return An SmimeInfo object with the specified certificate.
   */
  public static SmimeInfo createSmimeInfo(String filename, String password) {
    SmimeInfo smimeInfo = null;
    InputStream in = null;

    try {
      File file = new File(filename);
      in = new FileInputStream(file);
      byte[] fileContent = new byte[(int) file.length()];
      in.read(fileContent);

      smimeInfo = new SmimeInfo();
      smimeInfo.setPkcs12(Base64.getUrlEncoder().encodeToString(fileContent));
      if (password != null && password.length() > 0) {
        smimeInfo.setEncryptedKeyPassword(password);
      }
    } catch (Exception e) {
      System.out.printf("An error occured while reading the certificate file: %s\n", e);
    } finally {
      try {
        if (in != null) {
          in.close();
        }
      } catch (IOException ioe) {
        System.out.printf("An error occured while closing the input stream: %s\n", ioe);
      }
    }
    return smimeInfo;
  }
}

Python

gmail/snippet/smime स्निपेट/create_smime_info.py
import base64


def create_smime_info(cert_filename, cert_password):
  """Create an smimeInfo resource for a certificate from file.
  Args:
    cert_filename: Name of the file containing the S/MIME certificate.
    cert_password: Password for the certificate file, or None if the file is not
        password-protected.
  Returns : Smime object, including smime information
  """

  smime_info = None
  try:
    with open(cert_filename, "rb") as cert:
      smime_info = {}
      data = cert.read().encode("UTF-8")
      smime_info["pkcs12"] = base64.urlsafe_b64encode(data).decode()
      if cert_password and len(cert_password) > 0:
        smime_info["encryptedKeyPassword"] = cert_password

  except (OSError, IOError) as error:
    print(f"An error occurred while reading the certificate file: {error}")
    smime_info = None

  return smime_info


if __name__ == "__main__":
  print(create_smime_info(cert_filename="xyz", cert_password="xyz"))

S/MIME सर्टिफ़िकेट अपलोड करना

सर्टिफ़िकेट अपलोड करने के लिए, smimeInfo.insert को कॉल करें और अनुरोध के मुख्य हिस्से में smimeInfo रिसॉर्स दें:

Java

gmail/snippets/src/main/java/InsertSmimeInfo.java
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;

/* Class to demonstrate the use of Gmail Insert Smime Certificate API*/
public class InsertSmimeInfo {
  /**
   * Upload an S/MIME certificate for the user.
   *
   * @param userId      User's email address.
   * @param sendAsEmail The "send as" email address, or null if it should be the same as userId.
   * @param smimeInfo   The SmimeInfo object containing the user's S/MIME certificate.
   * @return An SmimeInfo object with details about the uploaded certificate, {@code null} otherwise.
   * @throws IOException - if service account credentials file not found.
   */
  public static SmimeInfo insertSmimeInfo(String userId,
                                          String sendAsEmail,
                                          SmimeInfo smimeInfo)
      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(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 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;
  }
}

Python

gmail/snippet/smime स्निपेट/insert_smime_info.py
import create_smime_info
import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError


def insert_smime_info():
  """Upload an S/MIME certificate for the user.
  Print the inserted certificate's id
  Returns : Result object with inserted certificate id and other 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)

    user_id = "gduser1@workspacesamples.dev"
    smime_info = create_smime_info.create_smime_info(
        cert_filename="xyz", cert_password="xyz"
    )
    send_as_email = None

    if not send_as_email:
      send_as_email = user_id

    # pylint: disable=maybe-no-member
    results = (
        service.users()
        .settings()
        .sendAs()
        .smimeInfo()
        .insert(userId=user_id, sendAsEmail=send_as_email, body=smime_info)
        .execute()
    )
    print(f'Inserted certificate; id: {results["id"]}')

  except HttpError as error:
    print(f"An error occurred: {error}")
    results = None

  return results


if __name__ == "__main__":
  insert_smime_info()

कई उपयोगकर्ताओं के सर्टिफ़िकेट मैनेज करने के उदाहरण

ऐसा हो सकता है कि आप संगठन के कई उपयोगकर्ताओं के सर्टिफ़िकेट एक साथ मैनेज करना चाहें. नीचे दिए गए उदाहरण में एक बैच कॉल में एक से ज़्यादा उपयोगकर्ताओं के लिए सर्टिफ़िकेट मैनेज करने का तरीका बताया गया है.

CSV फ़ाइल से प्रमाणपत्र शामिल किए जा रहे हैं

मान लें कि आपके पास एक CSV फ़ाइल है, जिसमें यूज़र आईडी और हर उपयोगकर्ता के सर्टिफ़िकेट का पाथ शामिल है:

$ cat certificates.csv
user1@example.com,/path/to/user1_cert.p12,cert_password_1
user2@example.com,/path/to/user2_cert.p12,cert_password_2
user3@example.com,/path/to/user3_cert.p12,cert_password_3

Java

CSV फ़ाइल में बताए गए सर्टिफ़िकेट को अपलोड करने के लिए, पहले से दिए गए createSmimeInfo और insertSmimeInfo कॉल का इस्तेमाल किया जा सकता है:

gmail/snippets/src/main/java/InsertCertFromCsv.java
import com.google.api.services.gmail.model.SmimeInfo;
import java.io.File;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;

/* 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(userId,
              userId,
              smimeInfo);
        } 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);
    }
  }
}

Python

CSV फ़ाइल में बताए गए सर्टिफ़िकेट को अपलोड करने के लिए, पहले से दिए गए create_smime_info और insert_smime_info कॉल का इस्तेमाल किया जा सकता है:

gmail/snippet/smime स्निपेट/insert_certificate_from_csv.py
import csv

import create_smime_info
import insert_smime_info


def insert_cert_from_csv(csv_filename):
  """Upload S/MIME certificates based on the contents of a CSV file.
  Each row of the CSV file should contain a user ID, path to the certificate,
  and the certificate password.

  Args:
    csv_filename: Name of the CSV file.
  """

  try:
    with open(csv_filename, "rb") as cert:
      csv_reader = csv.reader(cert, delimiter=",")
      next(csv_reader, None)  # skip CSV file header
      for row in csv_reader:
        user_id = row[0]
        cert_filename = row[1]
        cert_password = row[2]
        smime_info = create_smime_info.create_smime_info(
            cert_filename=cert_filename, cert_password=cert_password
        )
        if smime_info:
          insert_smime_info.insert_smime_info()
        else:
          print(f"Unable to read certificate file for user_id: {user_id}")
        return smime_info

  except (OSError, IOError) as error:
    print(f"An error occured while reading the CSV file: {error}")


if __name__ == "__main__":
  insert_cert_from_csv(csv_filename="xyz")

सर्टिफ़िकेट मैनेजमेंट

इस उदाहरण में smimeInfo API से किए गए कई कॉल को एक साथ जोड़कर दिखाया गया है कि आप अपने संगठन के लिए सर्टिफ़िकेट कैसे मैनेज कर सकते हैं. इसमें उपयोगकर्ता के लिए सर्टिफ़िकेट शामिल होता है. साथ ही, अगर डिफ़ॉल्ट सर्टिफ़िकेट की समयसीमा खत्म हो गई है या सेट नहीं किया गया है, तो यह बताई गई फ़ाइल में मौजूद सर्टिफ़िकेट को अपलोड कर देता है. इसके बाद, यह उस सर्टिफ़िकेट को सेट करता है जिसकी समयसीमा खत्म होने की तारीख, भविष्य में डिफ़ॉल्ट रूप से है.

इसके बाद, इसे उस फ़ंक्शन से कॉल किया जाता है जो CSV फ़ाइल को प्रोसेस करता है, जैसा कि पिछले उदाहरण में बताया गया था.

Java

gmail/snippets/src/main/java/UpdateSmimeCerts.java
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;

/* 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 certificate, {@code null} otherwise.
   * @throws IOException - if service account credentials file not found.
   */
  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(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 smimeInfo = CreateSmimeInfo.createSmimeInfo(certFilename,
            certPassword);
        SmimeInfo insertResults = InsertSmimeInfo.insertSmimeInfo(userId,
            sendAsEmail,
            smimeInfo);
        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;
  }
}

Python

gmail/snippet/smime स्निपेट/update_smime_certification.py
from datetime import datetime

import create_smime_info
import google.auth
import insert_smime_info
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError


def update_smime_cert(
    user_id, send_as_email, cert_filename, cert_password, expire_dt
):
  """Update S/MIME certificates for the user.

  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.

  Args:
    user_id: User's email address.
    send_as_email: The "send as" email address, or None if it should be the same
        as user_id.
    cert_filename: Name of the file containing the S/MIME certificate.
    cert_password: Password for the certificate file, or None if the file is not
        password-protected.
    expire_dt: DateTime object against which the certificate expiration is
      compared.  If None, uses the current time.

  Returns:
    The ID of the default certificate.

  Load pre-authorized user credentials from the environment.
  TODO(developer) - See https://developers.google.com/identity
  for guides on implementing OAuth2 for the application.
  """
  if not send_as_email:
    send_as_email = user_id

  creds, _ = google.auth.default()

  try:
    # create gmail api client
    service = build("gmail", "v1", credentials=creds)

    # pylint: disable=maybe-no-member
    results = (
        service.users()
        .settings()
        .sendAs()
        .smimeInfo()
        .list(userId=user_id, sendAsEmail=send_as_email)
        .execute()
    )

  except HttpError as error:
    print(f"An error occurred during list: {error}")
    return None

  default_cert_id = None
  best_cert_id = (None, datetime.datetime.fromtimestamp(0))

  if not expire_dt:
    expire_dt = datetime.datetime.now()
  if results and "smimeInfo" in results:
    for smime_info in results["smimeInfo"]:
      cert_id = smime_info["id"]
      is_default_cert = smime_info["isDefault"]
      if is_default_cert:
        default_cert_id = cert_id
      exp = datetime.datetime.fromtimestamp(smime_info["expiration"] / 1000)
      if exp > expire_dt:
        if exp > best_cert_id[1]:
          best_cert_id = (cert_id, exp)
      else:
        if is_default_cert:
          default_cert_id = None

  if not default_cert_id:
    default_id = best_cert_id[0]
    if not default_id and cert_filename:
      create_smime_info.create_smime_info(
          cert_filename=cert_filename, cert_password=cert_password
      )
      results = insert_smime_info.insert_smime_info()
      if results:
        default_id = results["id"]

    if default_id:
      try:
        # pylint: disable=maybe-no-member
        service.users().settings().sendAs().smimeInfo().setDefault(
            userId=user_id, sendAsEmail=send_as_email, id=default_id
        ).execute()
        return default_id
      except HttpError as error:
        print(f"An error occurred during setDefault: {error}")
  else:
    return default_cert_id

  return None


if __name__ == "__main__":
  update_smime_cert(
      user_id="xyz",
      send_as_email=None,
      cert_filename="xyz",
      cert_password="xyz",
      expire_dt=None,
  )