1.PC端登录163邮箱,点击设置按钮,找到POP3/SMTP/IMAP,需要开启它,如图:
2.开启授权密码,其中会叫你设置授权密码,设置完授权密码后如图:
3.添加maven依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
4.在springboot的配置文件中aplication.properties添加如下配置:
spring.mail.host=smtp.163.com //邮箱服务器 spring.mail.username=***@163.com //登录邮箱的账号 spring.mail.password=*** //这里填的是你刚才客户端授权的密码,而不是你登录邮箱的密码 spring.mail.default-encoding=UTF-8 spring.mail.protocol=smtps //协议 spring.mail.port=465 //邮箱服务器端口 spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.starttls.required=true
5.写一个mailservice类,发送简单纯文本的邮件:
@Component public class MyMailService { @Autowired private MailSender mailSender; public void send() { // new 一个简单邮件消息对象 SimpleMailMessage message = new SimpleMailMessage(); // 和配置文件中的的username相同,相当于发送方 message.setFrom("***@163.com"); // 收件人邮箱 message.setTo("***@163.com"); // 标题 message.setSubject("主题:xxxx"); // 正文 message.setText("信息拉取失败!"); // 发送 mailSender.send(message); } }