基于springboot的发送mail

发布时间:2019-09-24
技术:jdk-1.8 + springboot-2.1.0.RELEASE + maven-3.0.5

概述

在日常工作开发中,发送邮件功能有时需要我们去开发使用,这里首先介绍以下与发送接受邮件相关的一些协议: 发送邮件:SMPT、MIME,是一种基于"推"的协议,通过SMPT协议将邮件发送至邮件服务器,MIME协议是对SMPT协议的一种补充,如发送图片附件等 接收邮件:POP、IMAP,是一种基于"拉"的协议,收件人通过POP协议从邮件服务器拉取邮件

详细


一、运行效果


image.png

二、实现过程

①、添加依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>webjars-locator-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.3.7</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

②、创建核心服务service

   /**
     * 发送邮件
     */
    public MailVo sendMail(MailVo mailVo) {
        try {
            checkMail(mailVo); //1.检测邮件
            sendMimeMail(mailVo); //2.发送邮件
            return saveMail(mailVo); //3.保存邮件
        } catch (Exception e) {
            logger.error("发送邮件失败:", e);//打印错误信息
            mailVo.setStatus("fail");
            mailVo.setError(e.getMessage());
            return mailVo;
        }

    }


    //检测邮件信息类
    private void checkMail(MailVo mailVo) {
        if (StringUtils.isEmpty(mailVo.getTo())) {
            throw new RuntimeException("邮件收信人不能为空");
        }
        if (StringUtils.isEmpty(mailVo.getSubject())) {
            throw new RuntimeException("邮件主题不能为空");
        }
        if (StringUtils.isEmpty(mailVo.getText())) {
            throw new RuntimeException("邮件内容不能为空");
        }
    }

    //构建复杂邮件信息类
    private void sendMimeMail(MailVo mailVo) {
        try {
            MimeMessageHelper messageHelper = new MimeMessageHelper(mailSender.createMimeMessage(), true);//true表示支持复杂类型
            mailVo.setFrom(getMailSendFrom());//邮件发信人从配置项读取
            messageHelper.setFrom(mailVo.getFrom());//邮件发信人
            messageHelper.setTo(mailVo.getTo().split(","));//邮件收信人
            messageHelper.setSubject(mailVo.getSubject());//邮件主题
            messageHelper.setText(mailVo.getText());//邮件内容
            if (!StringUtils.isEmpty(mailVo.getCc())) {//抄送
                messageHelper.setCc(mailVo.getCc().split(","));
            }
            if (!StringUtils.isEmpty(mailVo.getBcc())) {//密送
                messageHelper.setCc(mailVo.getBcc().split(","));
            }
            if (mailVo.getMultipartFiles() != null) {//添加邮件附件
                for (MultipartFile multipartFile : mailVo.getMultipartFiles()) {
                    messageHelper.addAttachment(multipartFile.getOriginalFilename(), multipartFile);
                }
            }
            if (StringUtils.isEmpty(mailVo.getSentDate())) {//发送时间
                mailVo.setSentDate(new Date());
                messageHelper.setSentDate(mailVo.getSentDate());
            }
            mailSender.send(messageHelper.getMimeMessage());//正式发送邮件
            mailVo.setStatus("ok");
            logger.info("发送邮件成功:{}->{}", mailVo.getFrom(), mailVo.getTo());
        } catch (Exception e) {
            throw new RuntimeException(e);//发送失败
        }
    }


③、添加发送邮件页面

<div class="col-md-6" style="margin:20px;padding:20px;border: #E0E0E0 1px solid;">
    <marquee behavior="alternate" onfinish="alert(12)" id="mq"
             onMouseOut="this.start();$('#egg').text('嗯 真听话!');"
             onMouseOver="this.stop();$('#egg').text('有本事放开我呀!');">
        <h5 id="egg">祝大家新年快乐!</h5><img id="doge" src="http://pics.sc.chinaz.com/Files/pic/faces/3709/7.gif" alt="">
    </marquee>

    <form class="form-horizontal" id="mailForm">
        <div class="form-group">
            <label class="col-md-2 control-label">邮件发信人:</label>
            <div class="col-md-6">
                <input class="form-control" id="from" name="from" th:value="${from}" readonly="readonly">
            </div>
        </div>
        <div class="form-group">
            <label class="col-md-2 control-label">邮件收信人:</label>
            <div class="col-md-6">
                <input class="form-control" id="to" name="to" title="多个邮箱使用,隔开">
            </div>
        </div>
        <div class="form-group">
            <label class="col-md-2 control-label">邮件主题:</label>
            <div class="col-md-6">
                <input class="form-control" id="subject" name="subject">
            </div>
        </div>
        <div class="form-group">
            <label class="col-md-2 control-label">邮件内容:</label>
            <div class="col-md-6">
                <textarea class="form-control" id="text" name="text" rows="5"></textarea>
            </div>
        </div>
        <div class="form-group">
            <label class="col-md-2 control-label">邮件附件:</label>
            <div class="col-md-6">
                <input class="form-control" id="files" name="files" type="file" multiple="multiple">
            </div>
        </div>
        <div class="form-group">
            <label class="col-md-2 control-label">邮件操作:</label>
            <div class="col-md-3">
                <a class="form-control btn btn-primary" onclick="sendMail()">发送邮件</a>
            </div>
            <div class="col-md-3">
                <a class="form-control btn btn-default" onclick="clearForm()">清空</a>
            </div>
        </div>
    </form>

    <script th:inline="javascript">
        var appCtx = [[${#request.getContextPath()}]];

        function sendMail() {

            var formData = new FormData($('#mailForm')[0]);
            $.ajax({
                url: appCtx + '/mail/send',
                type: "POST",
                data: formData,
                contentType: false,
                processData: false,
                success: function (result) {
                    alert(result.status === 'ok' ? "发送成功!" : "你被Doge嘲讽了:" + result.error);
                },
                error: function () {
                    alert("发送失败!");
                }
            });
        }

        function clearForm() {
            $('#mailForm')[0].reset();
        }

        setInterval(function () {
            var total = $('#mq').width();
            var width = $('#doge').width();
            var left = $('#doge').offset().left;
            if (left <= width / 2 + 20) {
                $('#doge').css('transform', 'rotateY(180deg)')
            }
            if (left >= total - width / 2 - 40) {
                $('#doge').css('transform', 'rotateY(-360deg)')
            }
        });
    </script>
</div>

④、添加控制层

 /**
     * 发送邮件的主界面
     */
    @GetMapping("/")
    public ModelAndView index() {
        ModelAndView mv = new ModelAndView("mail/sendMail");//打开发送邮件的页面
        mv.addObject("from", mailService.getMailSendFrom());//邮件发信人
        return mv;
    }


    /**
     * 发送邮件
     */
    @PostMapping("/mail/send")
    public MailVo sendMail(MailVo mailVo, MultipartFile[] files) {
        mailVo.setMultipartFiles(files);
        return mailService.sendMail(mailVo);
    }

三、项目结构图

image.png


四、补充

Spring Boot的好处

1、配置简单;

2、编码简单;

3、部署简单;

4、监控简单


本实例支付的费用只是购买源码的费用,如有疑问欢迎在文末留言交流,如需作者在线代码指导、定制等,在作者开启付费服务后,可以点击“购买服务”进行实时联系,请知悉,谢谢
手机上随时阅读、收藏该文章 ?请扫下方二维码