1. 程式人生 > >Spring mvc +ajax 發送郵件

Spring mvc +ajax 發送郵件

緊急上線 ons true 表單提交 erl mtp tex json success

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=aaaa@163.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 發送郵件