常用的工具类
读取配置文件 CustomizedPropertyConfigurer.java
<context:annotation-config/> <bean id="propertyConfigurer" class="com.yyw.scs.framework.kit.CustomizedPropertyConfigurer"> <!-- 忽略没有找到的资源文件 --> <property name="ignoreResourceNotFound" value="true" /> <property name="locations"> <list> <value>file:/etc/dbprivatekey.properties</value> <value>classpath*:config/*.properties</value> <value>classpath*:sso.properties</value> <value>classpath*:email.properties</value> </list> </property> </bean>
package com.yyw.scs.framework.kit; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; import java.util.Properties; /** * configurations */ public class CustomizedPropertyConfigurer extends PropertyPlaceholderConfigurer { private static Properties ctxProperties; /** * encrypted keys */ private String[] encryptPropNames = {}; @Override protected String convertProperty(String propertyName, String propertyValue) { if (isEncryptProp(propertyName)) { return decode(propertyValue); } else { return propertyValue; } } private String decode(String value){ // has no encrypted items yet return value; // return Encrypter.decrypt(value); } @Override protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props) throws BeansException { super.processProperties(beanFactory, props); ctxProperties = props; } public static String getProperty(String name) { return ctxProperties.getProperty(name); } private boolean isEncryptProp(String propertyName) { for (String encryptpropertyName : encryptPropNames) { if (encryptpropertyName.equals(propertyName)) return true; } return false; } }
MailUtils.java
package com.yyw.scs.util; import com.yyw.scs.framework.kit.CustomizedPropertyConfigurer; import com.yyw.scs.model.Email; import com.yyw.scs.model.request.ImageMailDto; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.apache.velocity.app.VelocityEngine; import org.omg.CORBA.OBJ_ADAPTER; import org.springframework.ui.velocity.VelocityEngineUtils; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.*; import javax.mail.internet.*; import javax.mail.util.ByteArrayDataSource; import java.io.*; import java.util.*; /** * Created by zhouhaopeng on 2017/8/31. */ public class MailUtils { private static Logger log = Logger.getLogger(MailUtils.class); public static final String HTML_CONTENT = "text/html;charset=UTF-8"; public static final String ATTACHMENT_CONTENT = "text/plain;charset=gb2312"; private static VelocityEngine velocityEngine; /** * 发送邮件 * @param t 主体数据 * @param title 标题 * @param to 收件人 * @param bcc 抄送人 * @param templateName 模板路径名称 * @param <T> 返回 */ public <T extends List> void sendEmail(T t, String title, String[] to, String[] bcc, String templateName) { Map map = new HashMap(); map.put("datas", t); Email email = new Email.Builder(title, to, null).model(map).templateName(templateName).bcc(bcc).build(); sendEmail(email); } /** * 发送邮件 * @param t 主体数据 * @param imgPath 本地图片路径,使用路径读取图片显示 * @param title 标题 * @param to 收件人 * @param bcc 抄送人 * @param templateName 模板路径名称 * @param <T> 返回 */ public <T extends List> void sendEmail(T t, String imgPath, String title, String[] to, String[] bcc, String templateName) { Map map = new HashMap(); map.put("datas", t); map.put("imgPath", imgPath); Email email = new Email.Builder(title, to, null).model(map).templateName(templateName).bcc(bcc).build(); sendEmail(email); } /** * 发送邮件 * @param t 主体数据 * @param title 标题 * @param to 收件人 * @param bcc 抄送人 * @param templateName 模板路径名称 * @param imageData 图片附件数据,通过cid关联 * @param <T> 返回 */ public <T extends List> void sendEmail(T t, String title, String[] to, String[] bcc, String templateName, ImageMailDto[] imageData) { Map map = new HashMap(); map.put("datas", t); Email email = new Email.Builder(title, to, null).model(map).templateName(templateName).bcc(bcc).imageData(imageData).build(); sendEmail(email); } public <T extends List> void sendEmail(String title, String[] to, String[] bcc, String templateName, Map<String, Object> data) { Email email = new Email.Builder(title, to, null).model(data).templateName(templateName).bcc(bcc).build(); sendEmail(email); } public void sendEmail(String title, String[] to, String[] bcc, String content, byte[] data, String fileName, String fileType) { Email email = new Email.Builder(title, to, content).bcc(bcc).data(data).fileName(fileName).fileType(fileType).build(); sendEmail(email); } public <T extends List> void sendEmail(String title, String[] to, String[] bcc, String templateName, byte[] data, String fileName, String fileType, Map map) { Email email = new Email.Builder(title, to, null).model(map).templateName(templateName).bcc(bcc).data(data).fileType(fileType).fileName(fileName).build(); sendEmail(email); } public <T extends List> void sendEmail(T t, String title, String[] to, String[] bcc, String templateName, byte[] data, String fileName, String fileType) { Map map = new HashMap(); map.put("datas", t); Email email = new Email.Builder(title, to, null).model(map).templateName(templateName).bcc(bcc).data(data).fileType(fileType).fileName(fileName).build(); sendEmail(email); } public void sendEmail(String title, String[] to, String content) { Email email = new Email.Builder(title, to, content).bcc(null).build(); sendEmail(email); } public void sendEmail(String title, String[] to, String[] bcc, String content) { Email email = new Email.Builder(title, to, content).bcc(bcc).build(); sendEmail(email); } /** * 发送html模板邮件 */ private void sendEmail(Email email) { Long startTime = System.currentTimeMillis(); // 发件人 try { MimeMessage message = this.getMessage(email); // 新建一个存放信件内容的BodyPart对象 Multipart multiPart = new MimeMultipart(); MimeBodyPart mdp = new MimeBodyPart(); setContent(email); // 给BodyPart对象设置内容和格式/编码方式 mdp.setContent(email.getContent(), HTML_CONTENT); // 将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart) multiPart.addBodyPart(mdp); if (null != email.getData()) { MimeBodyPart attchment = new MimeBodyPart(); ByteArrayInputStream in = new ByteArrayInputStream(email.getData()); DataSource fds = new ByteArrayDataSource(in, email.getFileType()); attchment.setDataHandler(new DataHandler(fds)); attchment.setFileName(MimeUtility.encodeText(email.getFileName())); multiPart.addBodyPart(attchment); if (in != null) { in.close(); } } // 添加图片附件,使用cid关联在邮件正文中显示 if (email.getImageData() != null) { for (ImageMailDto dto : email.getImageData()) { MimeBodyPart image = new MimeBodyPart(); //javamail jaf image.setDataHandler(new DataHandler(new ByteArrayDataSource(dto.getImageData(), dto.getMimeType()))); image.setContentID(dto.getImageCid()); multiPart.addBodyPart(image); } } //把multiPart作为消息对象的内容 message.setContent(multiPart); message.saveChanges(); Transport.send(message); Long endTime = System.currentTimeMillis(); log.info("邮件发送成功 耗时:" + (endTime - startTime) / 1000 + "s"); } catch (Exception e) { log.error("Error while sending mail.", e); } } private Email setContent(Email email) { if (StringUtils.isEmpty(email.getContent())) { email.setContent(""); } if (StringUtils.isNotEmpty(email.getTemplateName()) && null != email.getModel()) { String content = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, email.getTemplateName(), "UTF-8", email.getModel()); email.setContent(content); } return email; } public void setVelocityEngine(VelocityEngine velocityEngine) { this.velocityEngine = velocityEngine; } private MimeMessage getMessage(Email email) { Properties props = new Properties(); String host = CustomizedPropertyConfigurer.getProperty("mail.smtp.host"); String port = CustomizedPropertyConfigurer.getProperty("mail.smtp.port"); String auth = CustomizedPropertyConfigurer.getProperty("mail.smtp.auth"); String username = CustomizedPropertyConfigurer.getProperty("mail.username"); String password = CustomizedPropertyConfigurer.getProperty("mail.password"); String from = CustomizedPropertyConfigurer.getProperty("mail.from"); props.put("mail.smtp.host", host); props.put("mail.stmp.port", port); props.put("mail.smtp.auth", auth); props.put("username", username); props.put("password", password); // 发件人 MimeMessage message = null; try { if (email.getTo() == null || email.getTo().length == 0 || StringUtils.isEmpty(email.getSubject())) { throw new Exception("接收人或主题为空"); } InternetAddress fromAddress = new InternetAddress(from); // toemails(字符串,多个收件人用,隔开) Session mailSession = Session.getDefaultInstance(props, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); message = new MimeMessage(mailSession); message.setFrom(fromAddress); for (String mailTo : email.getTo()) { message.addRecipient(Message.RecipientType.TO, new InternetAddress(mailTo)); } List<InternetAddress> ccAddress = new ArrayList<>(); if (null != email.getBcc()) { for (String mailCC : email.getBcc()) { ccAddress.add(new InternetAddress(mailCC)); } message.addRecipients(Message.RecipientType.CC, ccAddress.toArray(new InternetAddress[email.getBcc().length])); } message.setSentDate(new Date()); message.setSubject(email.getSubject()); } catch (Exception e) { log.error("Error while sending mail." + e.getMessage(), e); } return message; } public static void main(String [] args )throws Exception{ String[] toArr = {"wulei@111.com.cn", "zhanghui@111.com.cn", "zhanghui.it@qq.com"}; MailUtils mailUtils = new MailUtils(); mailUtils.sendEmail("测试邮件", toArr, "测试"); } }