码迷,mamicode.com
首页 > 编程语言 > 详细

使用 SpringBoot 配置发送邮件功能

时间:2019-05-19 09:43:34      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:ack   ide   frame   内容   img   cep   alibaba   inf   xxx   

1、使用 SpringBoot 配置发送邮件功能
项目总体结构

技术图片

用户表设计

SET FOREIGN_KEY_CHECKS=0;
CREATE DATABASE sample;
USE sample;
set names utf8;
-- ----------------------------
-- Table structure for tab_mail
-- ----------------------------
DROP TABLE IF EXISTS `tab_mail`;
CREATE TABLE `tab_mail` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(100) DEFAULT NULL,
  `password` varchar(100) DEFAULT NULL,
  `email` varchar(100) DEFAULT NULL,
  `active_code` varchar(100) DEFAULT NULL,
  `active_status` int(11) DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2、搭建 SpringBoot 环境

配置 pom.xml 文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.rookie</groupId>
    <artifactId>springboot-mail</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-mail</name>
    <description>Send mail project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.4</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.12</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
配置 application.yml 文件
# spring-boot-email
server:
  port: 8081

# 配置发送方信息
spring:
  mail:
    host: smtp.163.com
    username: xxxxxxx@163.com
    password: xxxxxxx                   # 填写客户端的授权码
    default-encoding: utf-8
    properties:
      mail:
        smtp:
          ssl:
            enable: true
# thymeleaf
  thymeleaf:
    cache: false

  mvc:
    date-format: yyyy-MM-dd

# mysql
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/sample?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT&useSSL=false
    type: com.alibaba.druid.pool.DruidDataSource

# mybatis
mybatis:
  mapper-locations: classpath:mapping/*.xml
  type-aliases-package: com.rookie.entity

代码演示

A、mapping & templates 文件夹下的 xml 文件
UserMapper.xml
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.rookie.dao.UserDao">
        <resultMap id="userMap" type="com.rookie.entity.User">
            <result property="id" column="id"/>
            <result property="username" column="username"/>
            <result property="password" column="password"/>
            <result property="email" column="email"/>
            <result property="activeStatus" column="active_status"/>
            <result property="activeCode" column="active_code"/>
        </resultMap>
        <insert id="insert" parameterType="com.rookie.entity.User">
            insert into tab_mail ( username, password,email,active_status,active_code)
            values (#{username}, #{password}, #{email},#{activeStatus},#{activeCode})
        </insert>

        <select id="findUserByActiveCode" parameterType="String" resultType="com.rookie.entity.User">
            select * from tab_mail where active_code = #{activeCode}
        </select>

        <!--激活账户,修改用户状态-->
        <update id="update" parameterType="com.rookie.entity.User">
            update tab_mail
            set active_status=#{activeStatus},username=#{username},password=#{password},
            email=#{email}, active_status=#{activeStatus},active_code=#{activeCode}
            where id=#{id}
        </update>

        <!--登录,根据 activeStatus=1 进行查询-->
        <select id="select" resultType="com.rookie.entity.User">
            select * from tab_mail where username=#{username} and password=#{password} and active_status=1
        </select>
    </mapper>
                    
=========================================================================================                                  
activeSuccess.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>激活成功</title>
    </head>
    <body>
        用户已激活!请<h1 style="color: green;"><a href="/user/loginPage">登录</a></h1>
    </body>
    </html>

=========================================================================================
error.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>错误</title>
    </head>
    <body>
    <h1 style="color: red;">用户不存在或未激活!</h1>
    <a href="/user/loginPage">登录</a>
    </body>
    </html>
 ========================================================================================= 
index.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>注册</title>
    </head>
    <body>
    <form action="/user/register" method="post">
        用户名:<input type="text" id="username" name="username"/><br>
        密码:<input type="password" id="password" name="password"/><br>
        邮箱:<input type="email" id="email" name="email"><br>
        <input type="submit" value="注册">
    </form>
    <a href="/user/loginPage">登录</a>
    </body>
    </html>
                    
========================================================================================= 
login.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>登录</title>
    </head>
    <body>
    <form action="/user/login" method="post">
        用户名:<input type="text" id="username" name="username"/><br>
        密码:<input type="password" id="password" name="password"/><br>
        <input type="submit" value="登录">
    </form>
    </body>
    </html>
                    
========================================================================================= 
success.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>注册成功</title>
    </head>
    <body>
    前往邮箱激活账户
    </body>
    </html>
                    
========================================================================================= 
welcome.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>欢迎</title>
    </head>
    <body>
    登录成功
    </body>
    </html>
========================================================================================= 
B、具体代码逻辑实现
public class IDUtils {
    public static String getUUID(){
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
}
========================================================================================= 
@Setter
@Getter
@ToString
public class User implements Serializable{
    private Integer id;
    private String username;
    private String password;
    private String email;
    private String activeCode;     // 激活码
    private Integer activeStatus;   // 激活状态 0 未激活 1 已激活
}
========================================================================================= 
@Controller
public class IndexController {

    @RequestMapping("/")
    public String index(){

        return "index";
    }
}
=========================================================================================
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 注册
     *
     * @param user
     * @return
     */
    @RequestMapping("/register")
    public String registerUser(User user) {
        user.setActiveStatus(0);
        user.setActiveCode(IDUtils.getUUID());
        userService.register(user);
        return "success";
    }

    /**
     * 激活校验码
     *
     * @param code
     * @return
     */
    @RequestMapping("/checkCode")
    public String checkCode(String code) {
        User user = userService.getUserByActiveCode(code);
        if (user != null) {
            user.setActiveStatus(1);
            user.setActiveCode("");
            userService.update(user);

            return "activeSuccess";
        }
        return "login";
    }


    /**
     * 跳转登陆页面
     *
     * @return login
     */
    @RequestMapping("/loginPage")
    public String login() {

        return "login";
    }

    /**
     * @param user
     * @return
     */
    @RequestMapping("/login")
    public String login(User user) {
        User userInfo = userService.getInfo(user);
        if (userInfo != null) {
            return "welcome";
        }
        return "error";
    }
}
========================================================================================= @Component
public interface UserDao {

    /**
     * 注册
     * @param user
     */
    void insert(User user);

    /**
     * 根据激活码查询用户
     * @param activeCode
     * @return User
     */
    User findUserByActiveCode(String activeCode);

    /**
     * 激活用户
     * @param user
     */
    void update(User user);

    /**
     *  查询用户
     * @param user
     * @return User
     */
    User select(User user);
}  
========================================================================================= 
@SpringBootApplication
@MapperScan(basePackages = "com.rookie.dao")
public class SpringbootMailApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootMailApplication.class, args);
    }

}  
=========================================================================================
public interface MailService {

    /**
     *  发送普通邮件
     * @param to        发给谁
     * @param subject   发送的主题
     * @param content   发送的内容
     */
    void sendMail(String to, String subject, String content);
}   

@Service
@Slf4j
public class MailServiceImpl implements MailService {

    @Autowired
    private JavaMailSenderImpl mailSender;

    @Value("${spring.mail.username}")
    private String from;

    @Override
    public void sendMail(String to, String subject, String content) {
        log.info("开始发送邮件:发送给 - >{},发送的主题 -> {},发送的内容 - >{}", to, subject, content);

        MimeMessage message;
        try {
            message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setSubject(subject);
            helper.setTo(to);
            helper.setText(content, true);
            mailSender.send(message);

            log.info("邮件发送成功");
        } catch (MessagingException e) {
            log.error("邮件发送失败",e);
        }
    }
}

========================================================================================= 
public interface UserService {

    /**
     * 用户注册
     * @param user
     */
    void register(User user);

    /**
     * 根据激活码找用户
     * @param activeCode
     * @return User
     */
    User getUserByActiveCode(String activeCode);

    /**
     * 修改用户
     * @param user
     */
    void update(User user);

    /**
     * 登陆
     * @param user
     * @return User
     */
    User getInfo(User user);
}

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao  userDao;

    @Autowired
    private MailService mailService;

    @Override
    public void register(User user) {
        userDao.insert(user);
        //获取激活码
        String code = user.getActiveCode();
        // System.out.println("激活码:"+code);
        //主题
        String subject = "来自 Rookie 的激活邮件";
        //上面的激活码发送到用户注册邮箱
        String context = "<a href='http://localhost:8081/user/checkCode?code="+code+"'>点击激活【Rookie网站】</a>";

        //发送激活邮件
        mailService.sendMail(user.getEmail(),subject,context);
    }

    @Override
    public User getUserByActiveCode(String activeCode) {
        return userDao.findUserByActiveCode(activeCode);
    }

    @Override
    public void update(User user) {
        userDao.update(user);
    }

    @Override
    public User getInfo(User user) {
        return userDao.select(user);
    }
}  

使用 SpringBoot 配置发送邮件功能

标签:ack   ide   frame   内容   img   cep   alibaba   inf   xxx   

原文地址:https://www.cnblogs.com/miantiao312/p/10887876.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!