Skip to content

Instantly share code, notes, and snippets.

@asgeirn
Created February 13, 2020 13:01
Show Gist options
  • Save asgeirn/eea5212d2c2fd538d8b63268082d4317 to your computer and use it in GitHub Desktop.
Save asgeirn/eea5212d2c2fd538d8b63268082d4317 to your computer and use it in GitHub Desktop.
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
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.auth.Credentials;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.ServiceAccountCredentials;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
public class GmailQuickstart {
private static final String SENDER = "sender@example.com";
private static final String RECIPIENT = "recipient@example.com";
private static final String APPLICATION_NAME = "Gmail API Java Quickstart";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final List<String> SCOPES = Collections.singletonList(GmailScopes.GMAIL_SEND);
private static final String CREDENTIALS_FILE_PATH = "credentials.json";
/**
* Creates an authorized Credential object.
*
* @param httpTransport The network HTTP Transport.
* @param jsonFactory The JSON factory.
* @param scopes Scopes to request.
* @param delegate User to assume.
* @return An authorized Credential object.
* @throws IOException If the credentials json file cannot be found.
*/
private static Credential getCredentials(final NetHttpTransport httpTransport, JsonFactory jsonFactory, List<String> scopes, String delegate) throws IOException {
// Load client secrets.
InputStream in = Files.newInputStream(Paths.get(CREDENTIALS_FILE_PATH));
return GoogleCredential.fromStream(in, httpTransport, jsonFactory).createScoped(scopes).createDelegated(delegate);
}
/**
* Create credentials using new google-auth-library-java
* @param scopes Scopes to request.
* @param delegate User to assume.
* @return Authorized Credentials.
* @throws IOException If the credentials file cannot be found.
*/
private static Credentials getCredentials(List<String> scopes, String delegate) throws IOException {
InputStream in = Files.newInputStream(Paths.get(CREDENTIALS_FILE_PATH));
return ServiceAccountCredentials.fromStream(in).createScoped(scopes).createDelegated(delegate);
}
/**
* Create a MimeMessage using the parameters provided.
*
* @param to email address of the receiver
* @param from email address of the sender, the mailbox account
* @param subject subject of the email
* @param bodyText body text of the email
* @return the MimeMessage to be used to send email
* @throws MessagingException
*/
public static MimeMessage createEmail(String to,
String from,
String subject,
String bodyText)
throws MessagingException {
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
MimeMessage email = new MimeMessage(session);
email.setFrom(new InternetAddress(from));
email.addRecipient(javax.mail.Message.RecipientType.TO,
new InternetAddress(to));
email.setSubject(subject);
email.setText(bodyText);
return email;
}
/**
* Create a message from an email.
*
* @param emailContent Email to be set to raw of message
* @return a message containing a base64url encoded email
* @throws IOException
* @throws MessagingException
*/
public static Message createMessageWithEmail(MimeMessage emailContent)
throws MessagingException, IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
emailContent.writeTo(buffer);
byte[] bytes = buffer.toByteArray();
String encodedEmail = Base64.encodeBase64URLSafeString(bytes);
Message message = new Message();
message.setRaw(encodedEmail);
return message;
}
/**
* Send an email from the user's mailbox to its recipient.
*
* @param service Authorized Gmail API instance.
* @param userId User's email address. The special value "me"
* can be used to indicate the authenticated user.
* @param emailContent Email to be sent.
* @return The sent message
* @throws MessagingException
* @throws IOException
*/
public static Message sendMessage(Gmail service,
String userId,
MimeMessage emailContent)
throws MessagingException, IOException {
Message message = createMessageWithEmail(emailContent);
message = service.users().messages().send(userId, message).execute();
System.out.println("Message id: " + message.getId());
System.out.println(message.toPrettyString());
return message;
}
public static void main(String... args) throws IOException, GeneralSecurityException, MessagingException {
// Build a new authorized API client service.
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
/*Gmail service = new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT, JSON_FACTORY, SCOPES, email))
.setApplicationName(APPLICATION_NAME)
.build();*/
Gmail service = new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, new HttpCredentialsAdapter(getCredentials(SCOPES, SENDER)))
.setApplicationName(APPLICATION_NAME)
.build();
sendMessage(service, "me", createEmail(RECIPIENT, SENDER, "Test", "This is a test!!"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment