SpringBoot进阶邮件服务(实战模拟邮箱注册含源码)

分析

工作中难免会用到邮箱服务,这里整理了五种邮件发送模式:发送文本邮件,发送HTML邮件,发送附件邮件,发送内联资源邮件,发送模板邮件。以供大家学习参考。最后实战部分模拟邮箱注册含源码。

看一下图(有图有真相)

SpringBoot进阶邮件服务(实战模拟邮箱注册含源码)_第1张图片

提前准备

pom.xml 配置


<dependencies>
    <dependency> 
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-mailartifactId>
    dependency> 
dependencies>

application.properties中添加邮箱配置

#邮箱服务器地址
spring.mail.protocol=smtp
spring.mail.host=smtp.qq.com
#邮箱服务器地址
spring.mail.username=************@qq.com
#邮箱密码
spring.mail.password=***********
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

注意:若是QQ spring.mail.password=QQ授权码,需要开启QQ授权码

SpringBoot进阶邮件服务(实战模拟邮箱注册含源码)_第2张图片

发送简单文本邮件

@RunWith(SpringRunner.class)
@SpringBootTest
public class EmailTests {

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private TemplateEngine templateEngine;

    //读取配置文件中的参数
    @Value("${spring.mail.username}")
    private String sender;

    private static final String recipient = "*************@163.com" ;

    /**
     * 发送简单文本邮件
     */
    @Test
    public void sendSimpleEmail() {
        SimpleMailMessage message = new SimpleMailMessage();
        // 发送者
        message.setFrom(sender);
        // 接收者
        message.setTo(recipient);
        //邮件主题
        message.setSubject("主题:文本邮件");
        // 邮件内容
        message.setText("骚扰邮件勿回");
        javaMailSender.send(message);
    }
}

发送HTML邮件

新增发送HTML邮件测试方法

/**
     * 发送Html邮件
     */
    @Test
    public void sendHtmlEmail() {
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(sender);
            helper.setTo(recipient);
            helper.setSubject("主题:HTML邮件");
            StringBuffer sb = new StringBuffer();
            sb.append("

大标题-h1

"
) .append("

红色字

"
) .append("

右对齐

"
); helper.setText(sb.toString(), true); } catch (MessagingException e) { throw new RuntimeException("Messaging Exception !", e); } javaMailSender.send(message); }

发送内联资源邮件

新增发送内联资源邮件测试方法

/**
     * 发送内联资源邮件
     */
    @Test
    public void sendInlineResourceMail() {
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(sender);
            helper.setTo(recipient);
            helper.setSubject("主题:这是有图片的邮件");
            String imgId = "avatar";
            String content="宫崎骏电影图片: + imgId + "\' >";
            helper.setText(content, true) ;
            FileSystemResource res = new FileSystemResource(new File("src/main/resources/static/images/avatar.jpg"));
            helper.addInline(imgId, res);
        } catch (MessagingException e) {
            throw new RuntimeException("Messaging  Exception !", e);
        }
        javaMailSender.send(message);
    }

发送模板邮件 重点

pom中导入thymeleaf的包

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-thymeleafartifactId>
dependency>

新增模板emailTemplate.html


<html lang="zh" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8"/>
        <title>Javazhan验证邮件title>
    head>
    <body>
        您好,这是验证邮件,请点击下面的链接完成验证,
        <a href="#" th:href="@{ http://www.javazhan.com/user/activation/{id}(id=${id}) }">激活账号a>。
    body>
html>

新增发送模板邮件测试方法

    /**
     * 发送模板邮件
     */
    @Test
    public void sendTemplateMail() {
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(sender);
            helper.setTo(recipient);
            helper.setSubject("主题:模板邮件");

            Context context = new Context();
            context.setVariable("id", "wenter");
            String emailContent = templateEngine.process("emailTemplate", context);
            helper.setText(emailContent, true);
        } catch (MessagingException e) {
            throw new RuntimeException("Messaging  Exception !", e);
        }
        javaMailSender.send(message);
    }

注:很多时候邮采用异步的方式来发送邮件,加快主交易执行速度,在实际项目中可以采用MQ发送邮件相关参数,监听到消息队列之后启动发送邮件。

实战部分模拟邮箱注册
很多网站都支持邮箱注册,以下将实现邮箱注册
功能:支持登录,注册,激活,重置密码。

效果如图
SpringBoot进阶邮件服务(实战模拟邮箱注册含源码)_第3张图片

注册成功

SpringBoot进阶邮件服务(实战模拟邮箱注册含源码)_第4张图片

未激活登录

SpringBoot进阶邮件服务(实战模拟邮箱注册含源码)_第5张图片

激活邮件 去激活

SpringBoot进阶邮件服务(实战模拟邮箱注册含源码)_第6张图片

激活后,登录成功

SpringBoot进阶邮件服务(实战模拟邮箱注册含源码)_第7张图片

重置密码

SpringBoot进阶邮件服务(实战模拟邮箱注册含源码)_第8张图片

重置密码邮件

SpringBoot进阶邮件服务(实战模拟邮箱注册含源码)_第9张图片

输入之前的密码登陆

SpringBoot进阶邮件服务(实战模拟邮箱注册含源码)_第10张图片

输入重置密码登陆

SpringBoot进阶邮件服务(实战模拟邮箱注册含源码)_第11张图片

错误邮箱提示

SpringBoot进阶邮件服务(实战模拟邮箱注册含源码)_第12张图片

代码

引入架包,修改pom.xml

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starterartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-context-supportartifactId>
            <version>RELEASEversion>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-thymeleafartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-mailartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        
        <dependency>
            <groupId>com.google.code.gsongroupId>
            <artifactId>gsonartifactId>
            <version>2.8.2version>

新建实体类User.java与RequestData.java
略了(看代码)

导入静态资源
css/js/….

编写js

$("#js-btn").click(function() {
    var data = {} ;
    var name = $("#js-btn").attr('class') ;
    var url = "" ;
    if(name.indexOf("rtn")>0) {
        data.userEmail = $("#js-field__email").val() ;
        data.userPass = $("#js-field__pass").val() ;
        url = "/user/login" ;
    } else if(name.indexOf("new")>0) {
        data.userEmail = $("#js-field__email").val() ;
        data.userPass = $("#js-field__pass").val() ;
        data.userRepass = $("#js-field__r-pass").val() ;
        url = "/user/register" ;
    } else if(name.indexOf("rst")>0) {
        data.userEmail = $("#js-field__email").val() ;
        url = "/user/forget" ;
    }
    submit(data, url) ;
});

function submit(data,url) {
    $.ajax({
        cache: !1,
        type: "POST",
        url: url,
        data: data,
        async: !0,
        beforeSend: function () {
            $("#js-btn").html("提交中..."), $("#js-btn").attr("disabled", "disabled")
        },
        success: function (data) {
            var result  = jQuery.parseJSON(data);
            layer.alert(result.message);
        },
        complete: function () {
            $("#js-btn").html("success"), $("#js-btn").removeAttr("disabled")
        }
    })
}

编写controler

/**
 * Created by yando on 2017/11/22.
 */
@RestController
@RequestMapping(value = "user")
public class UserController {

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private TemplateEngine templateEngine;

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

    private RequestData requestData = new RequestData() ;

    public static Map map = new HashMap();

    @RequestMapping(value = "login", method = RequestMethod.POST)
    public String login(User user) {
        for(User u : map.values()) {
            if(u!=null && u.getUserPass().equals(user.getUserPass()) && u.getUserEmail().equals(user.getUserEmail())) {
                if(u.getState()==0) {
                    requestData.setCode("9999");
                    requestData.setState("500");
                    requestData.setMessage("请前往"+user.getUserEmail()+"邮箱激活");
                    return new Gson().toJson(requestData);
                }
                requestData.setMessage("登录成功");
                return new Gson().toJson(requestData);
            }
        }
        requestData.setCode("9999");
        requestData.setState("500");
        requestData.setMessage("邮箱或者密码错误");
        return new Gson().toJson(requestData);

    }

    @RequestMapping(value = "register", method = RequestMethod.POST)
    public String register(User user) {
        map.put(user.getUserId(), user);
        // 发送注册邮件
        sendTemplateMail(user.getUserEmail(), user.getUserId());
        requestData.setMessage("注册成功, 快去激活");
        return new Gson().toJson(requestData);
    }
    @RequestMapping(value = "forget", method = RequestMethod.POST)
    public String forget(User user) {
        for(User u : map.values()) {
            if(u!=null || u.getUserEmail()== user.getUserEmail()) {
                u.setUserPass("6666");
                map.remove(u.getUserId());
                map.put(u.getUserId(), u);
                requestData.setMessage("密码已经重置,快去查看你的邮箱");
                sendSimpleEmail(u.getUserEmail(), "您好,您密码已重置,初始密码:6666,为了你的安全请尽快修改密码。");
                return new Gson().toJson(requestData);
            }
        }
        requestData.setCode("9999");
        requestData.setState("500");
        requestData.setMessage("无效邮箱");
        return new Gson().toJson(requestData);
    }
    @RequestMapping(value = "activation/{userId}", method = RequestMethod.GET)
    public void activation(@PathVariable String userId, HttpServletResponse response) throws IOException {
        User user = map.get(userId);
        if(user!=null) {
            user.setState(1);
            map.remove(user.getUserId());
            map.put(user.getUserId(), user);
        }
        response.sendRedirect("../../login.html");
    }

    public void sendSimpleEmail(String recipient,String text) {
        SimpleMailMessage message = new SimpleMailMessage();
        // 发送者
        message.setFrom(sender);
        // 接收者
        message.setTo(recipient);
        //邮件主题
        message.setSubject("Java资源分享网密码重置邮件");
        // 邮件内容
        message.setText(text);
        javaMailSender.send(message);
    }

    public void sendTemplateMail(String recipient,String userId) {
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(sender);
            helper.setTo(recipient);
            helper.setSubject("Java资源分享网验证邮件");
            Context context = new Context();
            context.setVariable("id", userId);
            String emailContent = templateEngine.process("emailTemplate", context);
            helper.setText(emailContent, true);
        } catch (MessagingException e) {
            throw new RuntimeException("Messaging  Exception !", e);
        }
        javaMailSender.send(message);
    }

}

结束了

执行RunApplication.java,看效果吧。

请测试邮件用自己的 不要给博主造成不必要的影响 谢谢

源码下载

SpringBoot进阶邮件服务(实战模拟邮箱注册含源码)

版权声明:本文为博主原创文章,未经博主允许不得转载。转载请注明出处:http://blog.csdn.net/wenteryan

你可能感兴趣的:(SpringBoot,Thymeleaf,后台,Spring,Boot,入门+实战(提供源码哟))