How do I call the gmail api in Spring Boot 2.x using a service account?

前端 未结 2 1193
暗喜
暗喜 2021-01-25 08:34

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 W

相关标签:
2条回答
  • 2021-01-25 09:17

    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");
    
    0 讨论(0)
  • 2021-01-25 09:32

    I had the same problem and finally, I solved it. I hope that solution helps others.

    Create a service account and delegate the right to GSuite.

    1. Go to google cloud console go-to service account
    2. Enable G Suite domain-wide Delegation
    3. Copy Client Id
    4. Login to your GSuite account. Go to Security -> API Controls -> Domain-wide Delegation
    5. Add your Client ID and scopes.
    6. and the final sample java code:

    @Value("${gcp.credentials.file}")
    private String CREDENTIALS_FILE_PATH;
    
    
    private static Credentials getCredentials(String CREDENTIALS_FILE_PATH) throws IOException {
        InputStream in = FileLoaderImpl.getStream(CREDENTIALS_FILE_PATH);
        if (in == null) {
            throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
        }
        GoogleCredentials credentials = GoogleCredentials
                .fromStream(in)
                .createDelegated(EMAIL_FROM)
                .createScoped(List.of(GmailScopes.GMAIL_SEND, GmailScopes.GMAIL_LABELS));
        return credentials;
    }
    
    private Gmail getGmailService() throws IOException, GeneralSecurityException {
        NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        return new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY,
                new HttpCredentialsAdapter(getCredentials(CREDENTIALS_FILE_PATH)))
                .setApplicationName(APPLICATION_NAME)
                .build();
    }
    
    @Override
    public Message sendMailWithTemplate(StarMail starMail, boolean isHtml) {
        try {
            MimeMessage mimeMessage = EmailUtils.createEmailMessage(starMail, isHtml);
            // MimeMessage mm = EmailUtils.createEmail(toEmail, USER_ID, subject, bodyText);
            Gmail service = getGmailService();
            Message message = EmailUtils.sendMessage(service, USER_ID, mimeMessage);
            LOGGER.info("Message id: {} ", message.getId());
            LOGGER.info(message.toPrettyString());
            return message;
        } catch (IOException | MessagingException | GeneralSecurityException e) {
            LOGGER.error("sending email failed {}", e);
            throw new RuntimeException("sending email failed " + e.getMessage());
        }
    }
    
    0 讨论(0)
提交回复
热议问题