无xml配置——使用Spring发送自定义模版邮件通知

依赖:spring-context-support-4.3.6.RELEASE.jar 

依赖:freemarker-2.3.23.jar


import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.mail.internet.MimeMessage;

import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import freemarker.cache.FileTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * 
 * Description:邮件发送类
 * Date:		2018年1月16日
 */
public class MailSender {
	
	private static JavaMailSenderImpl sender;

	private static Configuration configuration;

	private static ExecutorService executor;

	private MailSender() {
		init();
	}

	// 静态私有内部类用于实现线程安全的懒加载
	private static class MailSenderHolder {
		private static final MailSender instance = new MailSender();
	}

	public static final MailSender getInstance() {
		return MailSenderHolder.instance;
	}

	private void init() {
		System.out.println("初始化邮件发送MailSender类...");
		sender = getMailSender();
		configuration = getConfiguration();
		executor = Executors.newFixedThreadPool(4);
	}

	/**
	 * 
	 * Description:邮件发送类初始化
	 * Date:		2018年1月16日
	 * @author 		shaqf
	 * @email 		sqfsky@163.com
	 * @return
	 */
	private JavaMailSenderImpl getMailSender() {
		JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
		mailSender.setHost("smtp.exmail.izhichi.com");
		mailSender.setUsername("admin@izhichi.com");
		mailSender.setPassword("Admin@123456");
		mailSender.setProtocol("smtp");
		mailSender.setDefaultEncoding("UTF-8");
		Properties javaMailProperties = new Properties();
		javaMailProperties.setProperty("mail.smtp.auth", "true");
		javaMailProperties.setProperty("mail.smtp.from", "admin@izhichi.com");
		javaMailProperties.setProperty("mail.debug", "true");
		mailSender.setJavaMailProperties(javaMailProperties);
		return mailSender;
	}

	/**
	 * 
	 * Description:邮件模版初始化
	 * Date:		2018年1月16日
	 * @author 		shaqf
	 * @email 		sqfsky@163.com
	 * @return
	 */
	private Configuration getConfiguration() {
		try {
			FileTemplateLoader ftl1 = new FileTemplateLoader(new File(
					"E:\\zhuomian\\数据化运维平台\\智能运维平台\\svn\\disruptive\\manage\\src\\cn\\monitor\\bdweb\\email\\mailTemplate\\"));
			TemplateLoader[] loaders = new TemplateLoader[] { ftl1 };
			FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
			freeMarkerConfigurer.setPreTemplateLoaders(loaders);
			Properties settings = new Properties();
			settings.setProperty("template_update_delay", "1800");// 刷新模板的周期,单位为秒
			settings.setProperty("default_encoding", "UTF-8");// 模板的编码格式
			settings.setProperty("locale", "zh_CN"); // 本地化设置
			freeMarkerConfigurer.setFreemarkerSettings(settings);
			freeMarkerConfigurer.afterPropertiesSet();

			// 通过指定模板名获取FreeMarker模板实例
			Configuration configuration = freeMarkerConfigurer.getConfiguration();
			return configuration;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 
	 * Description:简单发送
	 * Date:		2018年1月16日
	 * @author 		shaqf
	 * @email 		sqfsky@163.com
	 * @param to	目标邮件地址
	 * @param title	邮件标题
	 * @param body	邮件内容
	 */
	public void sendSimpleMail(String to, String title, String body) {
		SimpleMailMessage smm = new SimpleMailMessage();
		smm.setFrom("admin@izhichi.com");
		smm.setTo(to);
		smm.setSubject(title);smm.setText(body);
		// 异步发送邮件
		executor.execute(new Runnable() {
			@Override
			public void run() {
				sender.send(smm);
			}
		});
	}
	
	/**
	 * 
	 * Description:通过模版发送数据
	 * Date:		2018年1月16日
	 * @author 		shaqf
	 * @email 		sqfsky@163.com
	 * @param to			目标邮件地址
	 * @param templateName	发送采用模版名称
	 * @param title			邮件标题
	 * @param templateData	用户动态数据
	 * @param fileName		附件完整名称(包含文件格式)
	 * @param file			附件封装File
	 */
	public void sendHtmlMail(String to, String templateName, String title, Map<String, ?> templateData, String fileName,
			File file) {
		try {
			// 使用JavaMail的MimeMessage,支付更加复杂的邮件格式和内容
			MimeMessage msg = sender.createMimeMessage();

			// 创建MimeMessageHelper对象,处理MimeMessage的辅助类
			MimeMessageHelper helper = new MimeMessageHelper(msg, true);

			// 使用辅助类MimeMessage设定参数
			helper.setFrom(sender.getUsername());
			helper.setTo(to);
			helper.setSubject(title);
			helper.setText(getMailText(templateName, templateData), true);

			// 加入附件
			if (file != null)
				helper.addAttachment(fileName, file);

			// 发送邮件
			executor.execute(new Runnable() {
				@Override
				public void run() {
					sender.send(msg);
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 
	 * Description:把动态数据注入到模版中
	 * Date:		2018年1月16日
	 * @author 		shaqf
	 * @email 		sqfsky@163.com
	 * @param templateName  指定模版
	 * @param templateData  用户数据
	 * @return
	 */
	private String getMailText(String templateName, Map<String, ?> templateData) {
		try {
			String htmlText = "";
			Template tpl = configuration.getTemplate(templateName);
			htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(tpl, templateData);
			return htmlText;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return templateData.toString();
	}

	private void sendHtmlMailTest() {
		Map<String, Object> templateData = new HashMap<>();
		templateData.put("email", "shaqf@izhichi.com");
		templateData.put("link", "http://www.izhichi.com");
		File file = new File("C:\\Users\\Administrator\\Desktop\\aa\\monitor-gateway.xls");
		MailSender.getInstance().sendHtmlMail("sqfsky@163.com", "testTemplate.ftl", "智能运维告警通知", templateData,
				"告警附件.xls", file);
	}

	public static void main(String[] args) {

		MailSender.getInstance().sendSimpleMail("shaqf@izhichi.com", "测试标题", "测试内容");

		// MailSender.getInstance().sendHtmlMailTest();
	}

}


模版testTemplate.ftl:

<html>
<head></head>
<body>
<table style="background:#ffffff" class="ecxbaidu_pass" bgcolor="" cellpadding="0" cellspacing="0" width="100%">
<tbody>
	<tr>
		<td>
		<table cellpadding="0" cellspacing="0" width="100%">
        <tbody>
		<tr>
			<td style="width:25px" width="25px;"></td>
			<td align="">
				<div style="line-height:40px;height:40px"></div>
				<p style="padding:0px"><strong style="font-size:14px;line-height:24px;color:#333333;font-family:arial,sans-serif">尊敬的${email}用户:</strong></p>
				<p style="padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:'\005b8b\004f53',arial,sans-serif">您好!</p>
				<p style="padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:'\005b8b\004f53',arial,sans-serif">您好!这是一封您订阅的告警邮件通知。</p>
				<p style="padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:'\005b8b\004f53',arial,sans-serif">1、您可以通过***平台平台进行相关问题的处理。</p>
				<p style="padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:'\005b8b\004f53',arial,sans-serif">2、您如果忘记密码,点击<a href="${link}" style="line-height:24px;font-size:12px;font-family:arial,sans-serif;color:#0000cc" target="_blank">「忘记密码」</a> 来找回密码。</p>
				<div style="line-height:80px;height:80px"></div>
				<p style="padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:'\005b8b\004f53',arial,sans-serif">专注自动化运维服务的运维平台</p>
				<p style="padding:0px;line-height:24px;font-size:12px;color:#333333;font-family:'\005b8b\004f53',arial,sans-serif">Copyright disruptive Corporation. All rights reserved. 版权所有</p>
			</td>
		</tr>
		</tbody>
		</table>
		</td>
	</tr>
</tbody>
</table>
</body>
</html>



没有更多推荐了,返回首页