S/MIME সার্টিফিকেট পরিচালনা

Gmail S/MIME API একটি Google Workspace ডোমেনে ব্যবহারকারীদের জন্য S/MIME ইমেল শংসাপত্রগুলি পরিচালনা করতে প্রোগ্রাম্যাটিক অ্যাক্সেস প্রদান করে।

সার্টিফিকেটগুলি কাজ করার জন্য একজন প্রশাসককে অবশ্যই ডোমেনের জন্য S/MIME সক্ষম করতে হবে৷

S/MIME স্ট্যান্ডার্ড পাবলিক কী এনক্রিপশন এবং MIME ডেটা স্বাক্ষর করার জন্য একটি স্পেসিফিকেশন প্রদান করে। ব্যবহারকারীর অ্যাকাউন্টে S/MIME শংসাপত্রগুলি কনফিগার করার ফলে Gmail নিম্নলিখিত উপায়ে সেই শংসাপত্রটি ব্যবহার করতে পারে:

  • আউটগোয়িং মেল সাইন করার জন্য Gmail ব্যবহারকারীর শংসাপত্র এবং ব্যক্তিগত কী ব্যবহার করে।
  • ইনকামিং মেল ডিক্রিপ্ট করতে Gmail ব্যবহারকারীর ব্যক্তিগত কী ব্যবহার করে।
  • Gmail বহির্গামী মেল এনক্রিপ্ট করতে প্রাপকের শংসাপত্র এবং সর্বজনীন কী ব্যবহার করে।
  • Gmail ইনকামিং মেল যাচাই করতে প্রেরকের শংসাপত্র এবং সর্বজনীন কী ব্যবহার করে।

আপনি পৃথক S/MIME সার্টিফিকেট তৈরি করেন এবং API ব্যবহার করে আপলোড করেন। প্রতিটি S/MIME শংসাপত্র একটি ব্যবহারকারী ইমেল অ্যাকাউন্টের জন্য একটি নির্দিষ্ট উপনামের জন্য। উপনামগুলির মধ্যে প্রাথমিক ইমেল ঠিকানার পাশাপাশি কাস্টম "এই রূপে পাঠান" ঠিকানা অন্তর্ভুক্ত থাকে। প্রতিটি উপনামের জন্য একটি একক S/MIME শংসাপত্রকে ডিফল্ট হিসাবে চিহ্নিত করা হয়েছে৷

API অ্যাক্সেস অনুমোদন করা হচ্ছে

API-তে অ্যাক্সেস অনুমোদনের দুটি রূপ রয়েছে:

  1. আপনি কর্তৃপক্ষের ডোমেইন-ওয়াইড ডেলিগেশন সহ একটি পরিষেবা অ্যাকাউন্ট ব্যবহার করতে পারেন। এই শর্তাবলীর ব্যাখ্যার জন্য, প্রমাণীকরণ এবং অনুমোদন ওভারভিউ শর্তাবলী পড়ুন। এই বিকল্পটি সক্ষম করার বিষয়ে তথ্যের জন্য, কর্তৃপক্ষের ডোমেইন-ওয়াইড প্রতিনিধিদের সাথে একটি পরিষেবা অ্যাকাউন্ট তৈরি করুন দেখুন
  2. আপনি একটি Oauth2 অ্যাক্সেস টোকেন পেতে শেষ-ব্যবহারকারীর সম্মতি প্রয়োজন এমন একটি আদর্শ OAuth2 ফ্লো ব্যবহার করতে পারেন। আরও তথ্যের জন্য, প্রমাণীকরণ এবং অনুমোদন ওভারভিউ পড়ুন এই বিকল্পটি ব্যবহার করার জন্য, ডোমেন প্রশাসককে অবশ্যই ডোমেন নিয়ন্ত্রণ প্যানেলে "S/MIME API শেষ ব্যবহারকারী অ্যাক্সেস সক্ষম" চেকবক্স সক্ষম করতে হবে৷

ACL স্কোপ

এই API জিমেইল sendAs পদ্ধতিগুলির মতো একই ACL স্কোপের উপর নির্ভর করে:

gmail.settings.basic
প্রাথমিক SendAs S/MIME আপডেট করার জন্য এই সুযোগ প্রয়োজন।
gmail.settings.sharing
S/MIME থেকে কাস্টম আপডেট করার জন্য এই সুযোগটি প্রয়োজন৷

API ব্যবহার করে

user.settings.sendAs.smimeInfo রিসোর্স সেই পদ্ধতিগুলি প্রদান করে যা আপনি S/MIME শংসাপত্রগুলি পরিচালনা করতে ব্যবহার করেন৷ প্রতিটি শংসাপত্র একজন ব্যবহারকারীর জন্য একটি পাঠান উপনামের সাথে যুক্ত।

একটি S/MIME কী আপলোড করুন৷

ব্যবহারকারীর অন্তর্গত একটি উপনামের জন্য একটি নতুন S/MIME কী আপলোড করতে smimeInfo.insert() পদ্ধতিটি ব্যবহার করুন৷ আপনি নিম্নলিখিত পরামিতি ব্যবহার করে লক্ষ্য উপনাম সনাক্ত করুন:

ব্যবহারকারী আইডি
ব্যবহারকারীর ইমেইল ঠিকানা. me বর্তমানে প্রমাণীকৃত ব্যবহারকারী নির্দেশ করতে বিশেষ মান ব্যবহার করতে পারেন।
sendAsEmail
যে উপনামের জন্য আপনি কী আপলোড করছেন। এই ইমেল ঠিকানাটি এই উপনাম ব্যবহার করে পাঠানো মেলের জন্য "থেকে:" শিরোনামে প্রদর্শিত হয়৷

S/MIME শংসাপত্র এবং ব্যক্তিগত কী সেই বিন্যাসে pkcs12 ক্ষেত্রে উপস্থিত থাকা উচিত; অনুরোধে অন্য কোন ক্ষেত্র সেট করা উচিত নয়। PKCS12 ফিল্ডে ব্যবহারকারী S/MIME কী এবং সাইনিং সার্টিফিকেট চেইন উভয়ই থাকবে বলে আশা করা হচ্ছে। API এটি গ্রহণ করার আগে এই ক্ষেত্রের মান যাচাই করে, নিম্নলিখিতগুলি যাচাই করে:

  • বিষয় নির্দিষ্ট ইমেল ঠিকানা মেলে.
  • মেয়াদোত্তীর্ণ বৈধ.
  • ইস্যুকারী শংসাপত্র কর্তৃপক্ষ (CA) আমাদের বিশ্বস্ত তালিকায় রয়েছে।
  • শংসাপত্রগুলি Gmail-এর প্রযুক্তিগত সীমাবদ্ধতার সাথে মেলে৷

যদি কীটি এনক্রিপ্ট করা থাকে তবে পাসওয়ার্ডটি encryptedKeyPassword ক্ষেত্রে থাকা উচিত। সফল সন্নিবেশ() কলগুলি smimeInfo-এর আইডি ফিরিয়ে দেবে যা ভবিষ্যতে কী উল্লেখ করতে ব্যবহার করা যেতে পারে।

একজন ব্যবহারকারীর S/MIME কী তালিকাভুক্ত করুন

প্রদত্ত উপনামের জন্য প্রদত্ত ব্যবহারকারীর জন্য S/MIME কীগুলির তালিকা ফেরত দিতে smimeInfo.list() পদ্ধতিটি ব্যবহার করুন। আপনি নিম্নলিখিত পরামিতি ব্যবহার করে লক্ষ্য উপনাম সনাক্ত করুন:

ব্যবহারকারী আইডি
ব্যবহারকারীর ইমেইল ঠিকানা. me বর্তমানে প্রমাণীকৃত ব্যবহারকারী নির্দেশ করতে বিশেষ মান ব্যবহার করতে পারেন।
sendAsEmail
যে উপনামের জন্য কী তালিকাভুক্ত করতে হবে। এই ইমেল ঠিকানাটি এই উপনাম ব্যবহার করে পাঠানো মেলের জন্য "থেকে:" শিরোনামে প্রদর্শিত হয়৷

একটি উপনামের জন্য S/MIME কীগুলি পুনরুদ্ধার করুন৷

একটি ব্যবহারকারীর জন্য একটি নির্দিষ্ট সেন্ড-এজ অ্যালিয়াসের জন্য নির্দিষ্ট S/MIME কীগুলি ফেরত দিতে smimeInfo.get() পদ্ধতিটি ব্যবহার করুন৷ আপনি নিম্নলিখিত পরামিতি ব্যবহার করে লক্ষ্য উপনাম সনাক্ত করুন:

ব্যবহারকারী আইডি
ব্যবহারকারীর ইমেইল ঠিকানা. me বর্তমানে প্রমাণীকৃত ব্যবহারকারী নির্দেশ করতে বিশেষ মান ব্যবহার করতে পারেন।
sendAsEmail
যে উপনামের জন্য আপনি কীগুলি পুনরুদ্ধার করছেন৷ এই ইমেল ঠিকানাটি এই উপনাম ব্যবহার করে পাঠানো মেলের জন্য "থেকে:" শিরোনামে প্রদর্শিত হয়৷

একটি S/MIME কী মুছুন

একটি উপনাম থেকে নির্দিষ্ট S/MIME কী মুছে ফেলতে smimeInfo.delete() পদ্ধতি ব্যবহার করুন। আপনি নিম্নলিখিত পরামিতি ব্যবহার করে লক্ষ্য উপনাম সনাক্ত করুন:

ব্যবহারকারী আইডি
ব্যবহারকারীর ইমেইল ঠিকানা. me বর্তমানে প্রমাণীকৃত ব্যবহারকারী নির্দেশ করতে বিশেষ মান ব্যবহার করতে পারেন।
sendAsEmail
যে উপনামের জন্য আপনি কীগুলি পুনরুদ্ধার করছেন৷ এই ইমেল ঠিকানাটি এই উপনাম ব্যবহার করে পাঠানো মেলের জন্য "থেকে:" শিরোনামে প্রদর্শিত হয়৷
আইডি
SmimeInfo-এর জন্য অপরিবর্তনীয় আইডি।

একটি উপনামের জন্য ডিফল্ট S/MIME কী সেট করুন

smimeInfo.setDefault() পদ্ধতিটি ব্যবহার করুন নির্দিষ্ট S/MIME কীটিকে নির্দিষ্ট উপনামের জন্য ডিফল্ট হিসাবে চিহ্নিত করতে। আপনি নিম্নলিখিত পরামিতি ব্যবহার করে লক্ষ্য উপনাম সনাক্ত করুন:

ব্যবহারকারী আইডি
ব্যবহারকারীর ইমেইল ঠিকানা. me বর্তমানে প্রমাণীকৃত ব্যবহারকারী নির্দেশ করতে বিশেষ মান ব্যবহার করতে পারেন।
sendAsEmail
যে উপনামের জন্য আপনি কীগুলি পুনরুদ্ধার করছেন৷ এই ইমেল ঠিকানাটি এই উপনাম ব্যবহার করে পাঠানো মেলের জন্য "থেকে:" শিরোনামে প্রদর্শিত হয়৷
আইডি
SmimeInfo-এর জন্য অপরিবর্তনীয় আইডি।

কোডের উদাহরণ

নিম্নলিখিত কোড নমুনাগুলি একাধিক ব্যবহারকারীর সাথে একটি সংস্থার জন্য S/MIME শংসাপত্রগুলি পরিচালনা করতে API ব্যবহার করে প্রদর্শন করে৷

একটি S/MIME শংসাপত্রের জন্য একটি SmimeInfo সংস্থান তৈরি করা

নিম্নলিখিত কোড নমুনা ফাইল থেকে একটি শংসাপত্র পড়া, একটি base64url স্ট্রিং-এ এনকোডিং এবং smimeInfo রিসোর্সের pkcs12 ক্ষেত্রে বরাদ্দ করা দেখায়:

জাভা

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;
  }
}

পাইথন

gmail/snippet/smime snippets/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 সংস্থান সরবরাহ করুন:

জাভা

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;
  }
}

পাইথন

gmail/snippet/smime snippets/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

জাভা

আপনি createSmimeInfo ব্যবহার করতে পারেন এবং CSV ফাইলে উল্লেখিত শংসাপত্রগুলি আপলোড করতে আগে থেকে কলগুলি 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);
    }
  }
}

পাইথন

আপনি CSV ফাইলে উল্লেখিত শংসাপত্রগুলি আপলোড করতে আগে থেকে create_smime_info এবং insert_smime_info কলগুলি ব্যবহার করতে পারেন:

gmail/snippet/smime snippets/insert_cert_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 ফাইল প্রক্রিয়া করে।

জাভা

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;
  }
}

পাইথন

gmail/snippet/smime snippets/update_smime_cert.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,
  )