com.springstudy.utils.email.MimeMailService.java Source code

Java tutorial

Introduction

Here is the source code for com.springstudy.utils.email.MimeMailService.java

Source

/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.springstudy.utils.email;

import com.gmk.framework.common.config.Global;
import com.gmk.framework.common.utils.ListUtils;
import com.gmk.framework.common.utils.email.*;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * MIME?.
 * <p/>
 * Freemarker?html?, .
 *
 * @author calvin
 */
public class MimeMailService {

    private static final String DEFAULT_ENCODING = "utf-8";

    private static Logger logger = LoggerFactory.getLogger(MimeMailService.class);

    private JavaMailSender mailSender;

    private FreeMarkerConfigurer freeMarkerConfigurer;

    /**
     * ??MIME?.
     */
    public boolean sendNotificationMail(com.gmk.framework.common.utils.email.Email email) {
        try {
            MimeMessage msg = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(msg, true, DEFAULT_ENCODING);
            //??????
            String from = Global.getConfig("productName");
            if (StringUtils.isNotEmpty(email.getFrom())) {
                from = from + "-" + email.getFrom();
            }
            helper.setFrom(Global.getConfig("mailFrom"), from);
            helper.setTo(email.getAddress());
            if (StringUtils.isNotEmpty(email.getCc())) {
                String cc[] = email.getCc().split(";");
                helper.setCc(cc);//?
            }
            //
            helper.setSubject(email.getSubject());
            //
            if (StringUtils.isNotEmpty(email.getTemplate())) {
                String content = generateContent(email.getTemplate(), email.getContentMap());
                helper.setText(content, true);
            } else {
                helper.setText(email.getContent());
            }
            //
            if (ListUtils.isNotEmpty(email.getAttachment())) {
                for (File file : email.getAttachment()) {
                    helper.addAttachment(MimeUtility.encodeWord(file.getName()), file);
                }
            }
            mailSender.send(msg);
            logger.info("HTML??");
            return true;
        } catch (MessagingException e) {
            logger.error(email.getAddressee() + "-" + email.getSubject() + "-" + "", e);
        } catch (Exception e) {
            logger.error(email.getAddressee() + "-" + email.getSubject() + "-" + "??", e);
        }
        return false;
    }

    /**
     * Freemarker?html?.
     */
    private String generateContent(String template, Map context) throws MessagingException {
        try {
            Template template1 = freeMarkerConfigurer.getConfiguration().getTemplate(template, DEFAULT_ENCODING);
            return FreeMarkerTemplateUtils.processTemplateIntoString(template1, context);
        } catch (IOException e) {
            logger.error("?, FreeMarker??", e);
            throw new MessagingException("FreeMarker??", e);
        } catch (TemplateException e) {
            logger.error("?, FreeMarker?", e);
            throw new MessagingException("FreeMarker?", e);
        }
    }

    /**
     * ?classpath.
     */
    private File generateAttachment() throws MessagingException {
        try {
            Resource resource = new ClassPathResource("/email/mailAttachment.txt");
            return resource.getFile();
        } catch (IOException e) {
            logger.error(",?", e);
            throw new MessagingException("?", e);
        }
    }

    /**
     * SpringMailSender.
     */
    public void setMailSender(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    /**
     * Freemarker?,Freemarker ?.
     */
    /*public void setFreemarkerConfiguration(Configuration freemarkerConfiguration) throws IOException {
    // ?freemarkerConfigurationtemplateLoaderPath.
      template = freemarkerConfiguration.getTemplate("mailTemplate.ftl", DEFAULT_ENCODING);
    }*/
    public void setFreeMarkerConfigurer(FreeMarkerConfigurer freeMarkerConfigurer) {
        this.freeMarkerConfigurer = freeMarkerConfigurer;
    }
}