springcloud框架下的邮件发送
使用JMail来发送邮件
MailController:
package com.xxx.alarm.controller;
import com.xxx.alarm.service.JMailService;
import com.xxx.commons.result.Result;
import com.xxx.commons.result.ResultCodeEnum;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@Api(value = "邮件发送", tags = {"邮件发送"})
@RestController
@RequestMapping(value = "/mail")
public class MailController {
private Logger logger = LoggerFactory.getLogger(MailController.class);
@Autowired
private JMailService jMailService;
@RequestMapping(value = "/sendMail", method = RequestMethod.POST)
public Result sendMail(@RequestParam(value = "title") String title, @RequestParam(value = "context") String context) {
Result result = new Result();
try {
jMailService.mailToMultiple(title, context);
logger.info("邮件发送成功!");
result.setCode(200, "邮件发送成功!");
} catch (Exception e) {
logger.error("邮件发送异常!", e);
result.setCode(ResultCodeEnum.SYSTEMERROR.getCode(), "邮件发送异常");
}
return result;
}
}
service层:
package com.xxx.alarm.service;
import com.xxx.commons.logs.CommonLogs;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.Security;
import java.util.Date;
import java.util.Properties;
/**
*
*/
@Service
public class JMailService {
private Logger logger = LoggerFactory.getLogger(JMailService.class);
@Value("${mail.enable}")
private boolean mailEnable;
@Value("${spring.profiles.active}")
private String active;
@Value("${spring.mail.username}")
private String from;
@Value("${spring.mail.password}")
private String password;
@Value("${spring.mail.host}")
private String host;
@Value("${spring.mail.receivers}")
private String receivers;
@Autowired
private CommonLogs commonLogs;
/**
* 使用加密的方式,利用465端口进行传输邮件,开启ssl
*
* @param subject 为收件人邮箱
* @param message 发送的消息
*/
public void mailToMultiple(String subject, String message) {
if (!mailEnable) {
return;
}
String[] emailList = StringUtils.split(receivers, ",");
if (emailList.length <= 0) {
return;
}
try {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
//设置邮件会话参数
Properties props = new Properties();
//邮箱的发送服务器地址
props.setProperty("mail.smtp.host", host);
props.setProperty("spring.mail.default-encoding", "UTF-8");
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
//邮箱发送服务器端口,这里设置为465端口
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.auth", "true");
//获取到邮箱会话,利用匿名内部类的方式,将发送者邮箱用户名和密码授权给jvm
Session session = Session.getDefaultInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, password);
}
});
//通过会话,得到一个邮件,用于发送
MimeMessage msg = new MimeMessage(session);
//设置发件人
msg.setFrom(new InternetAddress(from));
//设置收件人,to为收件人,cc为抄送,bcc为密送
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receivers, false));
msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(from, false));
// msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(to, false));
msg.setSubject(subject, "utf-8");
//设置邮件消息
msg.setText("当前分支:" + active + "\n本机IP:" + getLocalIP() + "\n" + message, "utf-8");
//设置发送的日期
msg.setSentDate(new Date());
//调用Transport的send方法去发送邮件
Transport.send(msg);
} catch (Exception e) {
logger.error(e.getMessage(), e);
commonLogs.error("告警邮件是失败", "alarmMail", e.getMessage());
}
}
/**
* 获取本机IP
*
* @return
*/
private String getLocalIP() {
InetAddress address = null;
String ip = null;
try {
address = InetAddress.getLocalHost();
ip = address.getHostAddress();
} catch (UnknownHostException e) {
logger.error("getLocalIP", e);
}
return ip; //返回IP地址
}
}
JavaMailSender 邮件发送的配置:
# JavaMailSender 邮件发送的配置
mail.enable=true
spring.mail.host=smtp.163.com
spring.mail.username=XXXtest@163.com
spring.mail.password=password
spring.mail.port=465
spring.mail.receivers=接收人的地址
spring.mail.filterInfo=/匹配信息,/匹配信息,/匹配信息
下面这个注解是实现层匹配这个自定义的条件,需要删除这个逗号!!!!!
@Value("#{'${spring.mail.filterInfo}'.split(',')}")
pom.xml文件的配置:
<!--邮件发送-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
控制层和service层代码写好,直接调用邮件发送mailToMultiple()方法就可以了,可以配置一下自己的swagger,这样容易调试!!!!!!