Skip to content

Instantly share code, notes, and snippets.

@tom-haines
Created February 17, 2020 06:44
Show Gist options
  • Save tom-haines/3ec0c4535f247922c270254322b64a6a to your computer and use it in GitHub Desktop.
Save tom-haines/3ec0c4535f247922c270254322b64a6a to your computer and use it in GitHub Desktop.
Example send via google domain-wide delegation in GSuite
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.Base64;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.gmail.model.Message;
import com.google.common.collect.Lists;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;
import java.util.Random;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/*
* Example send email via GSuite service account via domain-wide delegation.
*/
public class TestDomainSend {
static GoogleCredential createCredential(HttpTransport transport, JsonFactory jsonFactory) throws Exception {
final String credentialJsonPath = System.getProperty("user.home") + "/.config/gcloud/service-cred-from-console.json";
try (InputStream credentialStream = new FileInputStream(credentialJsonPath)) {
final GoogleCredential firstPassCred = GoogleCredential.fromStream(credentialStream, transport, jsonFactory);
return new GoogleCredential.Builder()
.setTransport(transport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(firstPassCred.getServiceAccountId())
.setServiceAccountProjectId(firstPassCred.getServiceAccountProjectId())
.setServiceAccountPrivateKey(firstPassCred.getServiceAccountPrivateKey())
.setServiceAccountPrivateKeyId(firstPassCred.getServiceAccountPrivateKeyId())
// service accounts must act on behalf of an actual user and have scope
.setServiceAccountScopes(Lists.newArrayList(GmailScopes.GMAIL_COMPOSE, GmailScopes.GMAIL_SETTINGS_SHARING))
.setServiceAccountUser("a.real.gsuite.account@example.com")
.build();
}
}
public static void main(String[] args) throws Exception {
Gmail service = createService();
MimeMessage mimeMessage = new MimeMessage(Session.getDefaultInstance(new Properties()));
// any address that `a.real.gsuite.account@example.com` has send rights for
String fromAddress = "aliases.are.okay@example.com";
mimeMessage.setFrom(new InternetAddress(fromAddress));
String fooMsg = String.format("Hello world! %d", new Random().nextInt(200));
mimeMessage.setRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress("foo@example.com"));
mimeMessage.setText(fooMsg);
mimeMessage.setSubject(fooMsg);
Gmail.Users.Messages messages = service.users().messages();
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
mimeMessage.writeTo(baos);
String encodedEmail = Base64.encodeBase64URLSafeString(baos.toByteArray());
Message message = new Message();
message.setRaw(encodedEmail);
Message sentMessage = messages.send("me", message).execute();
System.out.println(sentMessage.toPrettyString());
}
}
static Gmail createService() throws Exception {
final NetHttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
final JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
return new Gmail.Builder(transport, jsonFactory, createCredential(transport, jsonFactory))
.setApplicationName("gmail-api-app")
.build();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment