1.在pom.xml中导入 spring-boot-starter-mail 依赖
1 2 3 4 5 6
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> <version>2.1.1.RELEASE</version> </dependency>
|
2.配置application.properties
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| # spring-mail spring.mail.host=smtp.qq.com spring.mail.username=2386615000@qq.com
# 先要去邮箱获取属于自己邮箱的授权码(注意 : 此授权码我已修改...无效了) spring.mail.password=sxwrwevodyldigb
spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.starttls.required=true
# 端口号,不设置默认为25,而端口号25现已被很多云服务商禁用,如果非要用25,需申请解封,这里使用端口号:465 spring.mail.port=465 spring.mail.properties.mail.smtp.socketFactory.port = 465 spring.mail.properties.mail.smtp.socketFactory.class = javax.net.ssl.SSLSocketFactory spring.mail.properties.mail.smtp.socketFactory.fallback = false
|
3.开放465端口号 , 注意:我使用的是centos7.3的版本,防火墙是firewall
1
| firewall-cmd --zone=public --add-port=465/tcp --permanent
|
3.重启防火墙,运行命令:
4.查看端口号是否开启,运行命令:
1
| firewall-cmd --query-port=465/tcp
|
5.如果是阿里云的服务器 , 还需进入服务器管理控制台,给防火墙465端口号添加规则
6.定义邮件发送工具类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| package com.bhy702.website.common.validateUtil;
import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender;
public class SendToMail{
public static void sendSimpleMail(JavaMailSender javaMailSender, String email,String username, String message){
SimpleMailMessage simpleMailMessage = new SimpleMailMessage(); simpleMailMessage.setFrom("bhy702"+"<"+"2386615000@qq.com"+">"); simpleMailMessage.setTo(email); simpleMailMessage.setSubject("【个人网站通知】:老大,有新增留言信息通知~~"); simpleMailMessage.setText(username+" : "+message); javaMailSender.send(simpleMailMessage); } }
|
7. service层 调用邮件发送工具类 : SendToMail.sendSimpleMail() 方法发送邮件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| package com.bhy702.website.service;
import com.bhy702.website.common.validateUtil.SendToMail; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.stereotype.Service;
@Service public class SendMessageService {
@Autowired private JavaMailSender javaMailSender;
public boolean sendMessageForMe(String email, String username, String message) { SendToMail.sendSimpleMail(javaMailSender,email,username,message); return true; } }
|