All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.threewks.spring.gmail.GmailSender Maven / Gradle / Ivy

The newest version!
package com.threewks.spring.gmail;

import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.util.Base64;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.model.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSendException;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

public class GmailSender extends JavaMailSenderImpl{
    public static final String CREDENTIAL_USER_ID = "gmail-credentials";
    private static final Logger LOGGER = LoggerFactory.getLogger(GmailSender.class);
    private static final String AUTHENTICATED_USER = "me";

    private final GoogleAuthorizationCodeFlow flow;
    private MimeMessageInterceptor messageInterceptor = MimeMessageInterceptor.unchanged();

    public GmailSender(GoogleAuthorizationCodeFlow gmailAuthorizationCodeFlow, List messageInterceptors) {
        this.flow = gmailAuthorizationCodeFlow;
        setMessageInterceptors(messageInterceptors);
    }

    @Override
    protected void doSend(MimeMessage[] mimeMessages, Object[] originalMessages) throws MailException {
        Gmail client = getClient();
        try {

            for (MimeMessage mimeMessage: mimeMessages) {
                Message message = createMessageWithEmail(messageInterceptor.apply(mimeMessage));
                sendWithClient(client, message);
            }
        } catch (MessagingException e) {
            throw new MailSendException("Address exception:", e);
        } catch (IOException e) {
            throw new MailSendException("Messaging exception", e);
        }
    }

    /**
     * Create a Message from an email
     *
     * @param email Email to be set to raw of message
     * @return Message containing base64url encoded email.
     * @throws IOException
     * @throws MessagingException
     */
    protected static Message createMessageWithEmail(MimeMessage email)
            throws MessagingException, IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        email.writeTo(baos);
        String encodedEmail = Base64.encodeBase64URLSafeString(baos.toByteArray());
        Message message = new Message();
        message.setRaw(encodedEmail);
        return message;
    }

    /**
     * @param credentialId is the id to save the {@link com.google.api.client.auth.oauth2.StoredCredential} in datastore used by oauth process
     *                     You can use any unique id to associate your gmail account.
     * @return gmail instance for the given credentialId
     */
    protected Gmail getClient(String credentialId) {
        try {
            LOGGER.info("Loading StoredCredential id %s", credentialId);
            return new Gmail.Builder(flow.getTransport(), flow.getJsonFactory(), flow.loadCredential(credentialId)).build();
        } catch (IOException e) {
            String message = String.format("Error loading stored credential for inbox %s: %s", credentialId, e.getMessage());
            LOGGER.error(message);
            throw new RuntimeException(message, e);
        }
    }

    void sendWithClient(Gmail client, Message message) throws IOException {
        client.users().messages().send(AUTHENTICATED_USER, message).execute();
    }

    /**
     * @return gmail instance. Saves the {@link com.google.api.client.auth.oauth2.StoredCredential}	 with id CREDENTIAL_USER_ID
     **/
    Gmail getClient() {
        return getClient(CREDENTIAL_USER_ID);
    }


    private GmailSender setMessageInterceptors(List messageInterceptors) {
        this.messageInterceptor = MimeMessageInterceptor.unchanged();
        for (MimeMessageInterceptor interceptor : messageInterceptors) {
            this.messageInterceptor = messageInterceptor.andThen(interceptor);
        }
        return this;
    }


}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy