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("\n","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("运行结果!!");*/
    }
}

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

  

原文地址:https://www.cnblogs.com/alasijia/p/9330934.html

时间: 2024-10-14 02:18:19

Spring mvc +ajax 发送邮件的相关文章

spring mvc+ajax 实现json格式数据传递

使用ajax传递JSON对象 下面示例为ajax发送json对象,返回json格式数据 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 $.ajax({ url: "api/user", type: "POST", timeout: txnTimeOut, async: true, dataType: "json", data: {username : "lucy"}

spring mvc ajax 提交复杂数组类型

The server refused this request because the request entity is in a format not supported by the requested resource for the requested method 1.Spring Mvc 配置 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.sp

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

问题描述:spring mvc中前端使用ajax发送请求,后台使用@ResponseBody直接写数据到响应体中, 返回一个字符串,ajax的success回调函数不执行,反而执行error的回调函数 上代码: ajax请求: $.ajax({                url:"/eCommerceSSM/updateAdmin",                type:"put",                data:JSON.stringify({a

summernote + spring mvc + ajax 上传图片 &lt;笔记&gt;

最近在做一个考试系统项目.其中实体答案有这样的需求,答案A,B,C,D 采用 文本和图片混搭的形式,并且文本也是富文本. 数据库中大概是这么存的 废话不多说开始上干货.... 一.首先在jsp页面导入文件 二.接着进行,summernote的初始化  ,这里我初始化了很多个 --------------------------------------------------- 效果图: 三.summernote的默认图片上传是直接将图片进行base64编码,然后放在,img标签的data(记不太

spring mvc ajax请求

jar包中增加 jackson-annotations-2.5.0.jar jackson-core-2.5.0.jar jackson-databind-2.5.0.jar springmvx.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="

Spring MVC ajax:post/get 的具体实现

Post 方式 1.自动注入 a. pom.xml ---- 配置Maven,添加必要的jar包 1 <!--用于 String-JSONObject 转换 --> 2 <dependency> 3 <groupId>org.json</groupId> 4 <artifactId>org.json</artifactId> 5 <version>chargebee-1.0</version> 6 </d

spring mvc ajax中文乱码的几种解决办法

使用spingmvc,在JS里面通过ajax发送请求,并返回json格式的数据,从数据库拿出来是正确的中文格式,展示在页面上就是错误的 ,研究了一下,有几种解决办法. 方法一: 在@RequestMapping里面加入produces = "text/html;charset=UTF-8" Java代码 @RequestMapping(value = "/configrole", method = RequestMethod.GET, produces = &quo

spring mvc ajax返回值乱码

加入如下配置: <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.ByteArrayHtt

spring mvc ajax file upload

function ajaxFileUploadPic(projectId,name,type) { $.ajaxFileUpload({ url : '${ctx}/projectPic/saveorupdate.jhtml?projectId='+projectId+'&name='+name+'&type='+type, //用于文件上传的服务器端请求地址 secureuri : false, //一般设置为false fileElementId : 'file', //文件上传空间的