如何使用服务帐户在Spring Boot 2.x中调用gmail API? [英] How do I call the gmail api in Spring Boot 2.x using a service account?

查看:54
本文介绍了如何使用服务帐户在Spring Boot 2.x中调用gmail API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个配置为访问公司用户gmail帐户的GSuite服务帐户,我已经在G Suite管理控制台中为它提供了所有权限,包括域范围访问.我创建了一个服务帐户,现在想使用凭据代表他们发送电子邮件.

I have a GSuite service account configured to access corporate user gmail accounts, I have provided it with all of the privileges in the G Suite Admin console including Domain Wide access. I create a service account and now want to use the credentials to send emails on their behalf.

到目前为止,这是我的代码:

Here is my code so far:

  public void gmailTest(){
  log.info("Gmail test");

  List<String> SCOPES = new ArrayList<String>(GmailScopes.all());
  // List<String> SCOPES = GmailScopes.all();
  InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("Program Name-12345678.json");

  try {
  if(resourceAsStream != null) {
    NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();

    log.info("Reading credential file");
    GoogleCredential credential = GoogleCredential.fromStream(resourceAsStream);
    log.info("Creating scopes");
    credential = credential.createScoped(SCOPES);

    log.info("building gmail api service");
    Gmail gmailService = new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName("ept-mailer").build();
    String user = "deusrex@mygenericdomain.com";

    log.info("calling gmail api");
    ListLabelsResponse listResponse = gmailService.users().labels().list(user).execute();
    log.info("call did not error");
    List<Label> labels = listResponse.getLabels();
    if (labels.isEmpty()) {
      System.out.println("No labels found.");
    } else {
      System.out.println("Labels:");
      for (Label label : labels) {
        System.out.printf("- %s\n", label.getName());
      }
    }
  }
  }
  catch (IOException | GeneralSecurityException ex) {
  log.error(ex.getMessage());
  }

这是我的特权:

 Email (Manage labels)  https://www.googleapis.com/auth/gmail.labels 
 https://www.googleapis.com/auth/gmail.metadata 
 Email (Read/Write)  https://www.googleapis.com/auth/gmail.modify 

这是我得到的错误:

 400 Bad Request
 {
   "code" : 400,
   "errors" : [ {
     "domain" : "global",
     "message" : "Bad Request",
     "reason" : "failedPrecondition"
   } ],
   "message" : "Bad Request"
 }

推荐答案

好吧,答案是创建凭据时必须指定用户.在较新版本的API中,此调用已更改为:.createDelegated().只需向用户发送您希望在其中模拟的电子邮件即可.

Ok the answer was that you MUST specify a user when creating the credential. In the newer version of the API this call has been changed to: .createDelegated(). Just put the users email that you wish to impersonate there.

 GoogleCredential credential = GoogleCredential.fromStream(resourceAsStream).createDelegated("deusrex@mygenericdomain.com");

这篇关于如何使用服务帐户在Spring Boot 2.x中调用gmail API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆