在 pom.xml 文件中引入邮件配置:
org.springframework.boot
spring-boot-starter-mail
# JavaMailSender 邮件发送的配置
spring.mail.host=smtp.china.com
[email protected]
spring.mail.password=123456
spring.mail.test-connection=false
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
# ssl 配置
spring.mail.port=465
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.ssl.enable=true
spring.mail.properties.mail.imap.ssl.socketFactory.fallback=false
spring.mail.properties.mail.smtp.ssl.socketFactory.class=com.fintech.modules.base.util.mail.MailSSLSocketFactory
注意:如果是https的,ssl配置必须有,如果不是可以不用加
3.1、新建邮件entity
package com.fintech.modules.sms.common.dto;
import java.io.InputStream;
import java.io.Serializable;
/**
* @Description: 邮件模型
* @author lc
* @date 2018年4月24日
*/
public class EmailModelDTO implements Serializable{
/**
* 序列化
*/
private static final long serialVersionUID = -8840079326802564269L;
/**
* 发送者
*/
private String from;
/**
* 接受者
*/
private String[] to;
/**
* 抄送
*/
private String[] cc;
/**
* 邮件主题
*/
private String subject;
/**
* 邮件内容
*/
private String text;
/**
* 附件路径
*/
private String path;
private InputStream is;
public EmailModelDTO(String from, String[] to, String[] cc, String subject, String text, InputStream is){
this.from = from;
this.to = to;
this.cc = cc;
this.subject = subject;
this.text = text;
this.is = is;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String[] getTo() {
return to;
}
public void setTo(String[] to) {
this.to = to;
}
public String[] getCc() {
return cc;
}
public void setCc(String[] cc) {
this.cc = cc;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public InputStream getIs() {
return is;
}
public void setIs(InputStream is) {
this.is = is;
}
}
3.2、创建邮件发送service
package com.fintech.modules.sms.common.service;
import javax.activation.DataSource;
import javax.mail.internet.MimeMessage;
import javax.mail.util.ByteArrayDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import com.fintech.modules.sms.common.dto.EmailModelDTO;
/**
* @Description: 邮件发送service
* @author lc
* @date 2018年4月24日
*/
@Service
public class MailService {
private static Logger logger = LoggerFactory.getLogger(MailService.class);
@Autowired
private JavaMailSender mailSender;
/**
* @Description: 发送简单文本邮件
* @author lc
*/
public void sendSimpleMail(EmailModelDTO email){
try {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(email.getFrom());
message.setTo(email.getTo());
message.setSubject(email.getSubject());
message.setText(email.getText());
if(email.getCc() != null){
message.setCc(email.getCc());
}
mailSender.send(message);
} catch (Exception e) {
logger.error("发送简单文本邮件异常!",e.getMessage());
}
}
/**
* @Description: 发送html邮件
* @author lc
*/
public void sendHtmlMail(EmailModelDTO email){
MimeMessage message = null;
try {
message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(email.getFrom());
helper.setTo(email.getTo());
helper.setSubject(email.getSubject());
// 发送htmltext值需要给个true,不然不生效
helper.setText(email.getText(), true);
if(email.getCc() != null){
helper.setCc(email.getCc());
}
mailSender.send(message);
} catch (Exception e) {
logger.error("发送简单文本邮件异常!",e.getMessage());
}
}
/**
* @Description: 发送带附件的邮件
* @author lc
*/
public void sendAttachmentsMail(EmailModelDTO email){
MimeMessage message = null;
try {
message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(email.getFrom());
helper.setTo(email.getTo());
helper.setSubject(email.getSubject());
helper.setText(email.getText());
if(email.getCc() != null){
helper.setCc(email.getCc());
}
// 用流的形式发送附件邮件
DataSource source = new ByteArrayDataSource(email.getIs(), "application/msexcel");
helper.addAttachment("短信发送失败记录.xls", source);
mailSender.send(message);
} catch (Exception e){
logger.error("发送带附件的邮件异常!",e.getMessage());
}
}
}
3.3、读取配置文件中的发送人参数
//读取配置文件中的参数
@Value("${spring.mail.username}")
private String from;
3.4、发送html邮件
@Autowired
private MailService mailService;
// 发送邮件
String[] to = null;
String subject = "短信发送失败通知("+DateUtils.getTimeStampStr(new Date())+")";
logger.info("短信平台通知邮件信息(邮件):{}", content);
to = str.toArray(new String[str.size()]);
EmailModelDTO email = new EmailModelDTO(from, to, null, subject, content, null);
mailService.sendHtmlMail(email);
3.5、发送带有附件邮件
/*
* @Description: 导出
* @author lc
*/
public void exportExcel(List list, String sysCode){
InputStream is = null;
String[] headers_book = { "任务ID", "短信平台", "业务系统", "手机号", "错误码", "错误信息", "备注", "统计时间", "短信内容"};
is = exportExcelService.exportExcel("短信发送失败记录",headers_book, list);
String text = "各位好:"+DateUtils.getReqDate(new Date())+"短信发送失败记录统计信息";
String subject = "短信发送失败记录";
String[] to = getEmailTo(sysCode);
// String[] cc = getEmailCc(sysCode);
EmailModelDTO email = new EmailModelDTO(from, to, null, subject, text, is);
logger.info("短信发送状态邮件信息 {}", JSONArray.toJSON(email));
mailService.sendAttachmentsMail(email);
}
4.1、MailSSLSocketFactory
package com.fintech.modules.base.util.mail;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
/**
* @Description: 邮件ssl
* @author lc
* @date 2018年5月31日
*/
public class MailSSLSocketFactory extends SSLSocketFactory {
private SSLSocketFactory factory;
public MailSSLSocketFactory() {
try {
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, new TrustManager[] { new MailTrustManager() }, null);
factory = sslcontext.getSocketFactory();
} catch (Exception ex) {
// ignore
}
}
public static SocketFactory getDefault() {
return new MailSSLSocketFactory();
}
@Override
public Socket createSocket() throws IOException {
return factory.createSocket();
}
@Override
public Socket createSocket(Socket socket, String s, int i, boolean flag) throws IOException {
return factory.createSocket(socket, s, i, flag);
}
@Override
public Socket createSocket(InetAddress inaddr, int i, InetAddress inaddr1, int j) throws IOException {
return factory.createSocket(inaddr, i, inaddr1, j);
}
@Override
public Socket createSocket(InetAddress inaddr, int i) throws IOException {
return factory.createSocket(inaddr, i);
}
@Override
public Socket createSocket(String s, int i, InetAddress inaddr, int j) throws IOException {
return factory.createSocket(s, i, inaddr, j);
}
@Override
public Socket createSocket(String s, int i) throws IOException {
return factory.createSocket(s, i);
}
@Override
public String[] getDefaultCipherSuites() {
return factory.getDefaultCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return factory.getSupportedCipherSuites();
}
}
4.2、MailTrustManager
package com.fintech.modules.base.util.mail;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
/**
* @Description: 邮箱信证管理
* @author lc
* @date 2018年5月31日
*/
public class MailTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] cert, String authType) {
// everything is trusted
}
public void checkServerTrusted(X509Certificate[] cert, String authType) {
// everything is trusted
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
源码地址
码云:https://gitee.com/lichao12/spring-boot2-mail