Sunday, December 18, 2016

Send Email Using Google OAuth & Java

Download source code & required jars from here

For get access token & google user id click here


package com.pkm.google_auth;

import com.google.api.client.googleapis.GoogleUtils;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
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.repackaged.org.apache.commons.codec.binary.Base64;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.model.MessagePartHeader;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.ByteArrayOutputStream;
import java.util.Properties;

/**
 * Created by pritom on 18/12/2016.
 */
public class SendMail {
    private static final String USER_ID = "118224585672607576118";
    private static final String ACCESS_TOKEN = "ya29.Ci-4A700L53csid7qv6786780mbRqI8hdwesj7H2RSRnBizwfWFUY0pzYsx_xa-XZA";

    public static void main(String[] args) throws Exception {
        sendMail();
    }

    private static void sendMail() throws Exception {
        Properties props = new Properties();
        Session mailSession = Session.getInstance(props, new javax.mail.Authenticator() {

        });
        MimeMessage message = new MimeMessage(mailSession);

        message.setSubject("Test subject", "UTF-8");
        message.addRecipient(Message.RecipientType.TO, new InternetAddress("pritom@xxxxx.com", "Pritom Kumar"));

        Multipart multipart = new MimeMultipart();
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent("<DIV><B>BOLD HTML BODY</B></DIV>", "text/html");
        multipart.addBodyPart(messageBodyPart);

        message.addHeader("CUSTOM_HEADER_1", "CUSTOM_HEADER_1_VALUE");
        message.addHeader("CUSTOM_HEADER_2", "CUSTOM_HEADER_2_VALUE");

        message.setContent(multipart );

        GoogleCredential credential = new GoogleCredential().setAccessToken(ACCESS_TOKEN);
        Gmail gmail = new Gmail.Builder(_createHttpTransport(), _createJsonFactory(), credential).build();

        com.google.api.services.gmail.model.Message email = createMessageWithEmail(message);
        email = gmail.users().messages().send(USER_ID, email).execute();
        String emailID = email.getId(), messageID = getUniqueMessageIDByEMailId(emailID);
        System.out.println("EMAIL_SEND_WITH_GOOGLE_MAIL_ID=" + emailID);
        System.out.println("EMAIL_SEND_WITH_UNIQUE_MAIL_ID=" + messageID);
    }

    private static String getUniqueMessageIDByEMailId(String emailID) throws Exception {
        GoogleCredential credential = new GoogleCredential().setAccessToken(ACCESS_TOKEN);
        Gmail gmail = new Gmail.Builder(_createHttpTransport(), _createJsonFactory(), credential).build();
        com.google.api.services.gmail.model.Message message = gmail.users().messages().get(USER_ID, emailID).execute();
        for (MessagePartHeader messagePartHeader : message.getPayload().getHeaders()) {
            if (messagePartHeader.getName().equalsIgnoreCase("Message-ID")) {
                emailID = messagePartHeader.getValue().substring(1, messagePartHeader.getValue().length() - 1);
            }
        }
        return emailID;
    }

    private static com.google.api.services.gmail.model.Message createMessageWithEmail(MimeMessage email) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        email.writeTo(baos);
        String encodedEmail = Base64.encodeBase64URLSafeString(baos.toByteArray());
        com.google.api.services.gmail.model.Message message = new com.google.api.services.gmail.model.Message();
        message.setRaw(encodedEmail);
        return message;
    }

    private static HttpTransport _createHttpTransport() throws Exception {
        return new NetHttpTransport.Builder()
                .trustCertificates(GoogleUtils.getCertificateTrustStore())
                .build();
    }

    private static JsonFactory _createJsonFactory() {
        return new JacksonFactory();
    }
}

No comments:

Post a Comment