<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2.在application.properties里配置如下信息:
spring.mail.properties.mail.smtp.connecttimeout=5000
spring.mail.properties.mail.smtp.timeout=3000
spring.mail.properties.mail.smtp.writetimeout=5000
spring.mail.host=xxxxxxx
spring.mail.username=xxxx
spring.mail.password=xxx
spring.mail.port=25
spring.mail.properties.mail.smtp.auth=true
//---------------------------------------------------------------
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* 基于spring-boot的邮件发送功能测试
* @author Dabria_ly
* 2017年8月10日
*/
@Component("mailtest")
@Controller
@RequestMapping("/Mailtest")
public class TestEMailUtil {
@Autowired
private JavaMailSender mailSender;//JavaMailSender邮件发送类
@ResponseBody
@RequestMapping("/toSendMail")
public String testSendMail(){
//邮件接收者,多个邮件用;分割
String mailReceivers = "mengjuan@paifenle.com;15800634725@163.com";
String subject = "邮件主题";//邮件主题
String body = "邮件内容";//邮件内容
if(EMailUtilsWay.sendMail(mailSender, mailReceivers, subject, body)){
return "邮件发送成功";
}else{
return "邮件发送失败";
}
}
}
//-------------------------------------------------------------------------------------------
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
/**
* 发送邮件的工具类(基于spring-boot的邮件发送功能)
* @author Dabria_ly
* 2017年8月10日
*
*/
@Component
public class EMailUtilsWay {
private static final Logger LOG = LoggerFactory.getLogger(EMailUtilsWay.class);
/**
* 发送预警邮件
* @param mailSender : JavaMailSender邮件发送类
* @param mailReceivers : 邮件接收者
* @param subject : 邮件主题
* @param body : 邮件内容
* @return
*/
public static boolean sendMail(JavaMailSender mailSender,String mailReceivers,String subject,String body) {
if (StringUtils.hasText(mailReceivers)) {
String[] mails = mailReceivers.split(";");
return sendMail(mailSender,mails, subject, body);
}
return false;
}
public static boolean sendMail(JavaMailSender mailSender,String[] mails,String subject,String body) {
try {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("nopo");//设置邮件发送者名称
message.setTo(mails);
message.setSubject(subject);
message.setText(body);
mailSender.send(message);
return true;
} catch (Exception ex) {
LOG.error(String.format("发送邮件失败,%s", mails), ex);
}
return false;
}
}