SpringBoot集成Mail
1.依赖配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2.配置文件
spring:
mail:
host: smtp.qq.com
username: 597165227@qq.com
password: xxxxxxxxxxxxxxxx
default-encoding: UTF-8
其中第一个host(邮件服务器地址)参数,不同的邮箱有所不同,上面是QQ邮箱的host。163邮箱为smtp.163.com、126邮箱为smtp.126.com。
username和password项为邮箱对应的用户名和密码,密码并不是登录密码,而是开启POP3之后设置的客户端授权密码。
以QQ邮箱为例,进行密码的配置和获取。首先登录QQ邮箱,找“设置”,“账户”。
3.发送邮件
@Service
@Slf4j
public class MailService {
@Autowired
JavaMailSender javaMailSender;
//发送邮件
public void sendMail(String from,String to,String title,String content){
MimeMessage message = javaMailSender.createMimeMessage();
try {
// 第二个参数true表示需要创建一个multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(title);
helper.setText(content, true);
javaMailSender.send(message);
} catch (MessagingException e){
log.error("发送邮件异常"+e.getMessage());
}
}
}
@Controller
public class MailController {
@Autowired
MailService mailService;
@Value("${spring.mail.username}")
String from;
//首页
@GetMapping("/")
public String index(){
return "index";
}
//发送邮件
@PostMapping("/sendMail")
@ResponseBody
public AjaxResult sendMail(String to,String title,String content){
mailService.sendMail(from,to,title,content);
return AjaxResult.success("发送成功");
}
}
<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>搜索</title>
<style>
</style>
</head>
<body>
收件人:<input name="to" id="to"/><br>
标题:<input name="title" id="title" /><br>
内容:<textarea name="content" id="content" style="width: 500px;height: 300px;"></textarea><br>
<button onclick="sendMail()">发送</button>
<script src="http://apps.bdimg.com/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function sendMail(){
$.post("[[@{/sendMail}]]",{to:$("#to").val(),title:$("#title").val(),content:$("#content").val()},function(result){
alert(result.msg);
},'json');
}
</script>
</body>
</html>