基于SpringBoot 实现注册发送邮件源代码及解释
导入依赖 springBoot 官方提供的邮件依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
完成效果为 用户注册了之后,得到该对象form 表单内的用户输入的邮箱,
把邮件发送给谁, 在配置文件内 appliction.yml 下 配置发送者的信息。
下图所示为:配置文件
附代码:
spring:
mail:
host: smtp.163.com
# 发送者账号
username: XXXXX@163.com
# 授权密码,非登录密码,这里的授权密码是第三方授权的密匙
password: 这里填写授权码
default-encoding: UTF-8
第三方如何获取授权码: https://jingyan.baidu.com/article/adc815139f60c2f723bf7385.html (复制,粘贴到网页参考)
Service 层代码如下:
package com.web.Service;
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 {
//发送者
@Value("${spring.mail.username}")
private String sender;
//发送邮件工具类
@Autowired
JavaMailSender javaMailSender;
//发送简单邮件
public void sendSimpleMailMessage(String to,String subject,String content){
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setTo(to);
simpleMailMessage.setSubject(subject);
simpleMailMessage.setFrom(sender);
simpleMailMessage.setText(content);
javaMailSender.send(simpleMailMessage);
}
}
接下来
控制层调用Service层的方法
package com.web.Controller;
import com.web.pojo.UseTable;
import com.web.service.MailService;
import com.web.service.UseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import java.util.List;
@Controller
public class UseControlller {
@Autowired
UseService service;
@Resource
MailService mailService;
@RequestMapping("insert")
public String insert(UseTable use ,Model model){
int result=service.insert(use);
if (result==0){
String msg="没有注册成功,请重新填写信息";
model.addAttribute("msg",msg);
return "sign_up";
}else { //这里得到你要发送邮件给谁, 标题 和内容
mailService.sendSimpleMailMessage(use.getUseMail(),"网页激活登录页面",
"http://localhost:8080/sign_in 恭喜你,注册成功请点击登录" );
}
return "active";
}
}
接下来 我们就可以进行尝试输入正确的邮箱。 就可以发送简单的邮件了