Spring mvc +ajax 发送邮件

Posted 笨笨的妞

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring mvc +ajax 发送邮件相关的知识,希望对你有一定的参考价值。

1.前端页面--form表单提交,通过发送按钮的id=“send”定位DOM,触发ajax请求

                <form class="form-horizontal" id="emailEdit" style="display: none;margin: 40px;">
                    <%--收件人--%>
                    <div class="form-group">
                        <label for="emailer" class="col-sm-2 control-label" >收件人</label>
                        <div class="col-sm-10" style="width: 82%" >
                            <textarea class="form-control" rows="3" name="emailer" id="emailer" placeholder="多个收件人,请以,隔开"></textarea>
                        </div>
                    </div>
                    <%--邮件标题--%>
                    <div class="form-group" >
                        <label for="taskName" class="col-sm-2 control-label">邮件标题</label>
                        <div class="col-sm-10" style="width: 82%" >
                            <input type="text" class="form-control" name="emailTitle" id="emailTitle" placeholder="邮件标题">
                        </div>
                    </div>
                    <%--正文--%>
                    <div class="form-group" >
                        <label for="accdescription" class="col-sm-2 control-label">正文</label>
                        <div class="col-sm-10" style="width: 82%" >
                            <textarea class="form-control" rows="10" name="emailContent" id="emailContent" placeholder="邮件正文"></textarea>
                        </div>
                    </div>
                    <div class="form-group" style="float: right;margin-right: 40px;margin-top: 30px">
                        <div class="col-sm-offset-2 col-sm-10" >
                            <button type="button" class="btn btn-success" id="send" style="background-color: #FF8C00" >发送</button>
                        </div>
                    </div>
                </form>

2.ajax请求

   formCheckClean清除校验格式的函数

   checkparam() 校验输入非空,以及邮箱格式是否正确的函数

 通过发送按钮的id--send的点击事件,触发ajax请求 

var index11;
        function formCheckClean(){
            $(‘.text-danger‘).remove();//首先清除提示的标签
            $("*").removeClass(‘has-error‘);//清除has-error错误样式
        }//校验样式清除函数
    //邮箱非空校验及格式校验函数
        function checkparam(){
            var flag=true;
            var emailer=$("#emailer").val();
            var emailTitle=$("#emailTitle").val();
            if(emailer == null || emailer == ""){
                $("#emailer").parent().parent().addClass(‘form-group has-error‘);
                $("#emailer").parent().after(‘<label class="control-label text-danger"  style="display:block;float: right;color: red"><i class="fa fa-times-circle-o"></i> 必填项不能为空!</label>‘);
                flag=false;
            }else{
                reg = /^w+((-w+)|(.w+))*@[A-Za-z0-9]+((.|-)[A-Za-z0-9]+)*.[A-Za-z0-9]+$/;
                var strList=emailer.split(",");
                var errorcount =0;
                var errormail ="";
                for(i=0;i<strList.length;i++){
                    if(!reg.test(strList[i])){
                        errormail=errormail+strList[i]+‘;‘;
                        errorcount++;
                    }
                }
                if(errorcount >=1){
                    // console.log("不符合要求的邮箱个数:"+errorcount);
                    $("#emailer").parent().parent().addClass(‘form-group has-error‘);
                    $("#emailer").parent().after(‘<label class="control-label text-danger" style="display:block;float: right;color: red"><i class="fa fa-times-circle-o"></i>‘+‘错误邮箱:‘+errormail+‘</label>‘);
                    flag=false;
                }
            }
            if(emailTitle == null || emailTitle == ""){
                $("#emailTitle").parent().parent().addClass(‘form-group has-error‘);
                $("#emailTitle").parent().after(‘<label class="control-label text-danger"   style="display:block;float: right;color: red"><i class="fa fa-times-circle-o"></i> 必填项不能为空!</label>‘);
                flag=false;
            }
           return flag;
        }
        //发送邮件函数
        $("button#send").unbind("click").click(function(){
            formCheckClean();
            var flag=checkparam();
            var reg=new RegExp("
","g"); //创建正则RegExp对象
            eContent=$("#emailContent").val().replace(reg,"<br/>");
            if(flag == true){
                document.getElementById("send").innerhtml = "发送中...";
                // $("#send").text("发送中...");
                $.ajax({
                    type : "post",
                    url : "/accident/SendEditEmail.do",
                    dataType:"json",
                    data: {"emailer":$("#emailer").val(),"emailTitle":$("#emailTitle").val(),"emailContent":eContent},
                    async : false,
                    success:function (data){
                        document.getElementById("send").innerHTML = "发送";
                        if(data= "ture"){
                            layer.alert("发送成功!", {icon: 6,skin: ‘layui-layer-lan‘,});
                            layer.close(index11)//关闭弹层
                            $("#functontestform").find(‘input[type=text],select,input[type=date],textarea‘).each(function() {
                                $(this).val(‘‘);
                            });//清空form表单并查询
                            $(‘#functionTestSelectTable‘).bootstrapTable(‘refresh‘);
                        }else {
                            layer.msg("发送失败,请稍后重试", {icon: 5,skin: ‘layui-layer-lan‘,});
                        }
                    }//success end

                });//ajax end
            }
        });

3.在controller中写发邮件的逻辑,获取前端ajax请求传来的参数,调用SendMail类中的sendMail函数,并传参

    /**
     * 发送邮件编辑
     *
     * @param response
     * @return
     * @throws Exception
     * @param: request
     */
    @RequestMapping(value = "/SendEditEmail.do")
    @ResponseBody
    public String SendEditEmail(@Valid @ModelAttribute("accident") Accident accident, BindingResult br,
                                Model model, HttpServletRequest req, HttpServletResponse response) throws Exception {
        response.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        //收件人
        String emailer = req.getParameter("emailer").trim();
        //邮件标题
        String emailTitle = req.getParameter("emailTitle").trim();
        //邮件内容
        String emailContent = req.getParameter("emailContent").trim();
        //处理文件内容使用
        ArrayList<String> list = new ArrayList<>();
        System.out.println(emailContent);
        //发送邮件
        String status="false";
        if(emailer != "" && emailTitle != "" && emailContent != "")
        {
            List emailerList = new ArrayList();//不能使用string类型的类型,这样只能发送一个收件人
            String []median=emailer.split(",");//对输入的多个邮件进行逗号分割
            for(int i=0;i<median.length;i++){
                emailerList.add(new InternetAddress(median[i]));
            }
            InternetAddress[] address =(InternetAddress[])emailerList.toArray(new InternetAddress[emailerList.size()]);
//            System.out.println("收件人所在数组-----"+address);
            for(int i=0;i<address.length;i++){
                status=SendMail.sendMail(address[i],emailTitle,emailContent);
            }
        }
        return status;
    }

 4.在这之前需要配置邮箱信息 ------global.properties

#设置邮箱服务器
mailHost=smtp.163.com #设置邮箱端口号 mailPort=25 #设置邮箱服务器的用户名 mailUsername[email protected].com #授权码(注意不是邮箱登录密码) mailPassword=BMT856 #设置超时时间 mailTimeout=25000 #设置发件人 mailFrom[email protected]

5.开发获取配置文件的工具类

package luckyweb.seagull.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author lw
 * @createTime 2018/6/25 15:27
 * @description 获取配置文件类
 */
public class ProUtil {
    private static final String PROPERTIES_DEFAULT = "global.properties";
    public static String host;
    public static Integer port;
    public static String userName;
    public static String passWord;
    public static String emailForm;
    public static String timeout;
    public static String personal;
    public static Properties properties;/**
     * 初始化
     */
    private static void init() {
        properties = new Properties();
        try {
            InputStream inputStream = ProUtil.class.getClassLoader().getResourceAsStream(PROPERTIES_DEFAULT);
            properties.load(inputStream);
            inputStream.close();
            //properties.setProperty("mailFrom","[email protected]");
            host = properties.getProperty("mailHost");
            port = Integer.parseInt(properties.getProperty("mailPort"));
            userName = properties.getProperty("mailUsername");
            passWord = properties.getProperty("mailPassword");
            emailForm = properties.getProperty("mailFrom");
            timeout = properties.getProperty("mailTimeout");
            personal = "测试部";//发件人的别名
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

6.开发发送邮件的实现类

package luckyweb.seagull.util;

import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

/**
 * @author lw
 * @createTime 2018/6/25 15:24
 * @description 服务端邮件类
 */
public class SendMail {
    private static final String HOST = ProUtil.host;
    private static final Integer PORT = ProUtil.port;
    private static final String USERNAME = ProUtil.userName;
    private static final String PASSWORD = ProUtil.passWord;
    private static final String emailForm = ProUtil.emailForm;
    private static final String timeout = ProUtil.timeout;
    private static final String personal = ProUtil.personal;
    private static JavaMailSenderImpl mailSender = createMailSender();
    private SendMail(){}
    /**
     * 邮件发送器
     *
     * @return 配置信息工具
     */
    private static JavaMailSenderImpl createMailSender() {
        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        sender.setHost(HOST);
        sender.setPort(PORT);
        sender.setUsername(USERNAME);
        sender.setPassword(PASSWORD);
        sender.setDefaultEncoding("Utf-8");
        Properties p = new Properties();
        p.setProperty("mail.smtp.timeout", timeout);
        p.setProperty("mail.smtp.auth", "true");
        sender.setJavaMailProperties(p);
        return sender;
    }

    /**
     * 发送邮件
     *
     * @param to 接受人
     * @param subject 主题
     * @param html 发送内容
     * @throws :MessagingException 异常
     * @throws :UnsupportedEncodingException 异常
     */
    public static String sendMail(InternetAddress to, String subject, String html) throws MessagingException,UnsupportedEncodingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        // 设置utf-8或UTF-8编码,否则邮件会有乱码
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        messageHelper.setFrom(emailForm, personal);
        messageHelper.setTo(to);
        messageHelper.setSubject(subject);
        messageHelper.setText(html, true);
        mailSender.send(mimeMessage);
        return "true" ;
    }

    public static void main(String[] args) {
        String ss = "项目名称: 合肥通 事故状态: 跟踪处理完成 事故等级: 五级及以下事故 发生时间: 2018-06-11 13:52:42 事故原因类型: 紧急上线-未测试 事故描述: 线上事故 事故原因分析: 事故原因分析 受影响范围: 受影响范围 纠正处理过程: 纠正处理过程" +
                "(需点名责任人) 解决时间: 2018-06-11 13:53:25 事故汇报人: 张美丽";
        for (int i = 0; i < ss.length(); i++) {
            if(ss.equals(":"))
                break;
            String new_ss =ss.replace(" ","<br>");
            System.out.print(new_ss);
        }
           /* String subject = "html邮件测试"; // subject javamail自动转码

            StringBuffer theMessage = new StringBuffer();
            theMessage.append("<h2><font color=red>加油</font></h2>");
            theMessage.append("<hr>");
            theMessage.append("<i>美丽的开始</i>");
            theMessage.append("<table border=‘1‘><tr><td>aaa</td><td>bbb</td></tr><tr><td>ccc</td><td>ddd</td></tr></table>");


        try {
            SendMail.sendMail("[email protected]",subject,theMessage.toString());
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println("运行结果!!");*/
    }
}

 到此大功告成,支持发送多人,用,隔开。


  




以上是关于Spring mvc +ajax 发送邮件的主要内容,如果未能解决你的问题,请参考以下文章

Spring MVC 和表单绑定:如何从列表中删除项目?

mvc从前台发送ajax请求得到的数据显示未定义(undefined),哪位帮忙看看

将 JSON 数据传递给 Spring MVC 控制器

spring mvc ajax success不执行 反倒执行error

jquery的ajax与spring mvc对接注意事项

Rails ajax 表单发送电子邮件但不在“成功”下运行代码