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
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");
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.
@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());
}
}