com.szmslab.quickjavamail.send.MailSender.java Source code

Java tutorial

Introduction

Here is the source code for com.szmslab.quickjavamail.send.MailSender.java

Source

/*
 * Copyright (c) 2014 szmslab
 *
 * This software is released under the MIT License.
 * http://opensource.org/licenses/mit-license.php
 */
package com.szmslab.quickjavamail.send;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import org.apache.commons.lang3.StringUtils;

import com.szmslab.quickjavamail.utils.AttachmentFile;
import com.szmslab.quickjavamail.utils.InlineImageFile;
import com.szmslab.quickjavamail.utils.MailAddress;
import com.szmslab.quickjavamail.utils.MailProperties;

/**
 * JavaMail?????
 *
 * @author szmslab
 */
public class MailSender {

    /**
     * JavaMail?
     */
    private MailProperties properties;

    /**
     * ??? 
     */
    private boolean isDebug = false;

    /**
     * ? 
     */
    private boolean useDefaultSession = true;

    /**
     * ?
     */
    private Properties headers = new Properties();

    /**
     * 
     */
    private String charset;

    /**
     * From
     */
    private MailAddress fromAddress;

    /**
     * ReplyTo
     */
    private List<MailAddress> replyToAddressList = new ArrayList<MailAddress>();

    /**
     * To
     */
    private List<MailAddress> toAddressList = new ArrayList<MailAddress>();

    /**
     * Cc
     */
    private List<MailAddress> ccAddressList = new ArrayList<MailAddress>();

    /**
     * Bcc
     */
    private List<MailAddress> bccAddressList = new ArrayList<MailAddress>();

    /**
     * ??
     */
    private String subject;

    /**
     * (TEXT)
     */
    private String text;

    /**
     * (HTML)
     */
    private String html;

    /**
     * 
     */
    private List<AttachmentFile> attachmentFileList = new ArrayList<AttachmentFile>();

    /**
     * ?
     */
    private List<InlineImageFile> inlineImageFileList = new ArrayList<InlineImageFile>();

    /**
     * ??
     *
     * @param properties
     *            JavaMail?
     */
    public MailSender(MailProperties properties) {
        this.properties = properties;
        charset("ISO-2022-JP", "7bit");
    }

    /**
     * ??????
     *
     * @param isDebug
     *            ??????
     * @return ?
     */
    public MailSender debug(boolean isDebug) {
        this.isDebug = isDebug;
        return this;
    }

    /**
     * ????
     *
     * @param useDefaultSession
     *            ??????
     * @return ?
     */
    public MailSender useDefaultSession(boolean useDefaultSession) {
        this.useDefaultSession = useDefaultSession;
        return this;
    }

    /**
     * ????
     *
     * @param key
     *            ???
     * @param value
     *            ?
     * @return ?
     */
    public MailSender header(String key, String value) {
        if (StringUtils.isNotBlank(key) && StringUtils.isNotBlank(value)) {
            headers.setProperty(key, value);
        }
        return this;
    }

    /**
     * ???
     *
     * @param charset
     *            
     * @return ?
     */
    public MailSender charset(String charset) {
        if (StringUtils.isNotBlank(charset)) {
            this.charset = charset;
        }
        return this;
    }

    /**
     * ???
     *
     * @param charset
     *            
     * @param contentTransferEncoding
     *            Content-Transfer-Encoding?
     * @return ?
     */
    public MailSender charset(String charset, String contentTransferEncoding) {
        if (StringUtils.isNotBlank(charset)) {
            charset(charset);
            header("Content-Transfer-Encoding", contentTransferEncoding);
        }
        return this;
    }

    /**
     * From???
     *
     * @param address
     *            From
     * @return ?
     */
    public MailSender from(MailAddress address) {
        if (address != null) {
            fromAddress = address;
        }
        return this;
    }

    /**
     * ReplyTo???
     *
     * @param address
     *            ReplyTo
     * @return ?
     */
    public MailSender replyTo(MailAddress... addresses) {
        for (MailAddress address : addresses) {
            if (address != null) {
                replyToAddressList.add(address);
            }
        }
        return this;
    }

    /**
     * To???
     *
     * @param address
     *            To
     * @return ?
     */
    public MailSender to(MailAddress... addresses) {
        for (MailAddress address : addresses) {
            if (address != null) {
                toAddressList.add(address);
            }
        }
        return this;
    }

    /**
     * Cc???
     *
     * @param address
     *            Cc
     * @return ?
     */
    public MailSender cc(MailAddress... addresses) {
        for (MailAddress address : addresses) {
            if (address != null) {
                ccAddressList.add(address);
            }
        }
        return this;
    }

    /**
     * Bcc???
     *
     * @param address
     *            Bcc
     * @return ?
     */
    public MailSender bcc(MailAddress... addresses) {
        for (MailAddress address : addresses) {
            if (address != null) {
                bccAddressList.add(address);
            }
        }
        return this;
    }

    /**
     * ?????
     *
     * @param subject
     *            ??
     * @return ?
     */
    public MailSender subject(String subject) {
        if (StringUtils.isNotBlank(subject)) {
            this.subject = subject;
        }
        return this;
    }

    /**
     * (TEXT)???
     *
     * @param text
     *            (TEXT)
     * @return ?
     */
    public MailSender text(String text) {
        if (StringUtils.isNotBlank(text)) {
            this.text = text;
        }
        return this;
    }

    /**
     * (HTML)???
     *
     * @param text
     *            (HTML)
     * @return ?
     */
    public MailSender html(String html) {
        if (StringUtils.isNotBlank(html)) {
            this.html = html;
        }
        return this;
    }

    /**
     * ???
     *
     * @param files
     *            
     * @return ?
     */
    public MailSender attachmentFiles(AttachmentFile... files) {
        for (AttachmentFile file : files) {
            if (file != null) {
                attachmentFileList.add(file);
            }
        }
        return this;
    }

    /**
     * ????
     *
     * @param files
     *            ?
     * @return ?
     */
    public MailSender inlineImageFiles(InlineImageFile... files) {
        for (InlineImageFile file : files) {
            if (file != null) {
                inlineImageFileList.add(file);
            }
        }
        return this;
    }

    /**
     * ????
     *
     * @throws UnsupportedEncodingException
     * @throws MessagingException
     */
    public void execute() throws UnsupportedEncodingException, MessagingException {
        final Session session = useDefaultSession
                ? Session.getDefaultInstance(properties.getProperties(), properties.getAuthenticator())
                : Session.getInstance(properties.getProperties(), properties.getAuthenticator());
        session.setDebug(isDebug);

        final MimeMessage message = new MimeMessage(session);

        message.setFrom(fromAddress.toInternetAddress(charset));
        message.setReplyTo(toInternetAddresses(replyToAddressList));
        message.addRecipients(Message.RecipientType.TO, toInternetAddresses(toAddressList));
        message.addRecipients(Message.RecipientType.CC, toInternetAddresses(ccAddressList));
        message.addRecipients(Message.RecipientType.BCC, toInternetAddresses(bccAddressList));
        message.setSubject(subject, charset);

        setContent(message);

        message.setSentDate(new Date());

        Transport.send(message);
    }

    /**
     * MailAddress?InternetAddress???????
     *
     * @param addressList
     *            MailAddress?
     * @return InternetAddress??
     * @throws AddressException
     * @throws UnsupportedEncodingException
     */
    private InternetAddress[] toInternetAddresses(List<MailAddress> addressList)
            throws AddressException, UnsupportedEncodingException {
        InternetAddress[] arr = new InternetAddress[addressList.size()];
        for (int i = 0; i < addressList.size(); i++) {
            arr[i] = addressList.get(i).toInternetAddress(charset);
        }
        return arr;
    }

    /**
     * MimeMultipart????mulpart/mixed
     *
     * @return MimeMultipartmulpart/mixed?
     */
    private MimeMultipart createMixedMimeMultipart() {
        return new MimeMultipart();
    }

    /**
     * MimeMultipart????mulpart/alternative
     *
     * @return MimeMultipartmulpart/alternative?
     */
    private MimeMultipart createAlternativeMimeMultipart() {
        return new MimeMultipart("alternative");
    }

    /**
     * MimeMultipart????mulpart/related
     *
     * @return MimeMultipartmulpart/related?
     */
    private MimeMultipart createRelatedMimeMultipart() {
        return new MimeMultipart("related");
    }

    /**
     * MimeBodyPart????text/plain
     *
     * @return MimeBodyParttext/plain?
     * @throws MessagingException
     */
    private MimeBodyPart createTextPart() throws MessagingException {
        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setText(text, charset);
        setHeaderToPart(textPart);
        return textPart;
    }

    /**
     * MimeBodyPart????text/html
     *
     * @return MimeBodyParttext/html?
     * @throws MessagingException
     */
    private MimeBodyPart createHtmlPart() throws MessagingException {
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setText(html, charset, "html");
        setHeaderToPart(htmlPart);
        return htmlPart;
    }

    /**
     * MimeBodyPart????Content-Disposition: attachment
     *
     * @param file
     *            
     * @return MimeBodyPartContent-Disposition: attachment?
     * @throws MessagingException
     * @throws UnsupportedEncodingException
     */
    private MimeBodyPart createAttachmentPart(AttachmentFile file)
            throws MessagingException, UnsupportedEncodingException {
        MimeBodyPart attachmentPart = new MimeBodyPart();
        attachmentPart.setFileName(MimeUtility.encodeText(file.getFileName(), charset, null));
        attachmentPart.setDataHandler(new DataHandler(file.getDataSource()));
        attachmentPart.setDisposition(MimeBodyPart.ATTACHMENT);
        return attachmentPart;
    }

    /**
     * MimeBodyPart????Content-Disposition: inline
     *
     * @param file
     *            ?
     * @return MimeBodyPartContent-Disposition: inline?
     * @throws MessagingException
     * @throws UnsupportedEncodingException
     */
    private MimeBodyPart createImagePart(InlineImageFile file)
            throws MessagingException, UnsupportedEncodingException {
        MimeBodyPart imagePart = new MimeBodyPart();
        imagePart.setContentID(file.getContentId());
        imagePart.setFileName(MimeUtility.encodeText(file.getFileName(), charset, null));
        imagePart.setDataHandler(new DataHandler(file.getDataSource()));
        imagePart.setDisposition(MimeBodyPart.INLINE);
        return imagePart;
    }

    /**
     * ?????
     *
     * @param message
     *            
     * @throws MessagingException
     * @throws UnsupportedEncodingException
     */
    private void setContent(MimeMessage message) throws MessagingException, UnsupportedEncodingException {
        if (StringUtils.isBlank(html)) {
            if (attachmentFileList.isEmpty()) {
                /*
                 * text/plain
                 */
                message.setText(text, charset);
            } else {
                /*
                 * multipart/mixed
                 *  text/plain
                 *  attachment
                 */
                Multipart mixedMultipart = createMixedMimeMultipart();
                mixedMultipart.addBodyPart(createTextPart());
                for (AttachmentFile file : attachmentFileList) {
                    mixedMultipart.addBodyPart(createAttachmentPart(file));
                }
                message.setContent(mixedMultipart);
            }
        } else {
            if (attachmentFileList.isEmpty()) {
                if (inlineImageFileList.isEmpty()) {
                    /*
                     * multipart/alternative
                     *  text/plain
                     *  text/html
                     */
                    Multipart alternativeMultipart = createAlternativeMimeMultipart();
                    alternativeMultipart.addBodyPart(createTextPart());
                    alternativeMultipart.addBodyPart(createHtmlPart());
                    message.setContent(alternativeMultipart);
                } else {
                    /*
                     * multipart/alternative
                     *  text/plain
                     *  mulpart/related
                     *    text/html
                     *    image
                     */
                    Multipart relatedMultipart = createRelatedMimeMultipart();
                    relatedMultipart.addBodyPart(createHtmlPart());
                    for (InlineImageFile file : inlineImageFileList) {
                        relatedMultipart.addBodyPart(createImagePart(file));
                    }
                    MimeBodyPart relatedPart = new MimeBodyPart();
                    relatedPart.setContent(relatedMultipart);

                    Multipart alternativeMultipart = createAlternativeMimeMultipart();
                    alternativeMultipart.addBodyPart(createTextPart());
                    alternativeMultipart.addBodyPart(relatedPart);
                    message.setContent(alternativeMultipart);
                }
            } else {
                if (inlineImageFileList.isEmpty()) {
                    /*
                     * multipart/mixed
                     *  mulpart/alternative
                     *   text/plain
                     *   text/html
                     *  attachment
                     */
                    Multipart alternativeMultipart = createAlternativeMimeMultipart();
                    alternativeMultipart.addBodyPart(createTextPart());
                    alternativeMultipart.addBodyPart(createHtmlPart());
                    MimeBodyPart alternativePart = new MimeBodyPart();
                    alternativePart.setContent(alternativeMultipart);

                    Multipart mixedMultipart = createMixedMimeMultipart();
                    mixedMultipart.addBodyPart(alternativePart);
                    for (AttachmentFile file : attachmentFileList) {
                        mixedMultipart.addBodyPart(createAttachmentPart(file));
                    }
                    message.setContent(mixedMultipart);
                } else {
                    /*
                     * multipart/mixed
                     *  mulpart/alternative
                     *   text/plain
                     *   mulpart/related
                     *     text/html
                     *     image
                     *  attachment
                     */
                    Multipart relatedMultipart = createRelatedMimeMultipart();
                    relatedMultipart.addBodyPart(createHtmlPart());
                    for (InlineImageFile file : inlineImageFileList) {
                        relatedMultipart.addBodyPart(createImagePart(file));
                    }
                    MimeBodyPart relatedPart = new MimeBodyPart();
                    relatedPart.setContent(relatedMultipart);

                    Multipart alternativeMultipart = createAlternativeMimeMultipart();
                    alternativeMultipart.addBodyPart(createTextPart());
                    alternativeMultipart.addBodyPart(relatedPart);
                    MimeBodyPart alternativePart = new MimeBodyPart();
                    alternativePart.setContent(alternativeMultipart);

                    Multipart mixedMultipart = createMixedMimeMultipart();
                    mixedMultipart.addBodyPart(alternativePart);
                    for (AttachmentFile file : attachmentFileList) {
                        mixedMultipart.addBodyPart(createAttachmentPart(file));
                    }
                    message.setContent(mixedMultipart);
                }
            }
        }
        setHeaderToPart(message);
    }

    /**
     * ??????
     *
     * @param part
     *            ?
     * @throws MessagingException
     */
    private void setHeaderToPart(Part part) throws MessagingException {
        for (Iterator<Map.Entry<Object, Object>> itr = headers.entrySet().iterator(); itr.hasNext();) {
            Map.Entry<Object, Object> head = itr.next();
            part.setHeader(head.getKey().toString(), head.getValue().toString());
        }
    }

}