1引入依赖
<!--发送邮件依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2 邮件发送service
package com.bootdo.shop.mail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
@Service
public class MailService {
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String from;
//尴尬,只能网易给网易的发,网易给别的发就报错
public void sendMail(String title, String url, String email) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);//发送方
message.setTo(email);//收件人
message.setText(url);//信的内容
mailSender.send(message);
}
}
3 配置
spring.mail.password=hao12345这个是客户端授权码,不是登陆密码,详情请看我的上一篇
http://blog.csdn.net/xueer88888888888888/article/details/78550463
spring.mail.host=smtp.163.com
spring.mail.username=18434260757@163.com
spring.mail.password=hao12345
#开启邮箱验证
spring.mail.properties.mail.smtp.auth=true
#开启加密通讯
spring.mail.properties.mail.smtp.starttls.enable=true
#必须要经过加密进行通讯
spring.mail.properties.mail.smtp.starttls.required=true
4测试
package com.example.demo.mail2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class Send {
@Autowired
MailService mailService;
@RequestMapping(value = "/send")
@ResponseBody
public String sendmail() {
mailService.sendMail("通知", "你好,xueer,我想", "spring_boot@163.com");
return "chenggongle...";
}
}