美文网首页
发送邮件浅析

发送邮件浅析

作者: nzdnllm | 来源:发表于2019-03-05 09:19 被阅读0次

    1.编写javabean,MailInfo.class

    package com.xxx.javabean;
    
    
    public class MailInfo {
        //邮箱服务器 如smtp.263.net
        private String host ;
        //用户邮箱 如**@xxx.com
        private String formName ;
        //用户授权码 不是用户名密码 可以自行查看相关邮件服务器怎么查看
        private String formPassword ;
        //消息回复邮箱
        private String replayAddress ;
        //发送地址
        private String toAddress ;
        //发送主题
        private String subject ;
        //发送内容
        private String content ;
    
        public String getHost() {
            return host;
        }
        public void setHost(String host) {
            this.host = host;
        }
        public String getFormName() {
            return formName;
        }
        public void setFormName(String formName) {
            this.formName = formName;
        }
        public String getFormPassword() {
            return formPassword;
        }
        public void setFormPassword(String formPassword) {
            this.formPassword = formPassword;
        }
        public String getReplayAddress() {
            return replayAddress;
        }
        public void setReplayAddress(String replayAddress) {
            this.replayAddress = replayAddress;
        }
        public String getToAddress() {
            return toAddress;
        }
        public void setToAddress(String toAddress) {
            this.toAddress = toAddress;
        }
        
        public String getSubject() {
            return subject;
        }
        public void setSubject(String subject) {
            this.subject = subject;
        }
        public String getContent() {
            return content;
        }
        public void setContent(String content) {
            this.content = content;
        }
    }
    

    2.配置邮件的发送发和接收方的信息

    package com.xxx.servlet;
    
    import java.util.Date;
    import java.util.Properties;
    
    import javax.mail.Authenticator;
    import javax.mail.*;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
    import javax.mail.internet.MimeBodyPart;
    import javax.mail.internet.MimeMultipart;
    
    
    
    import com.xxx.javabean.MailInfo;
    public class SendJavaHtmlEmail {
        //定义发送邮件用户的邮箱信息
        private final static String host="邮箱host";
        private final static String formName="邮箱账号,如xxx@xx.com";
        private final static String password="邮箱密码";
        private final static String replayAddress="邮箱账号,如xxx@xx.com";
    
        public static void sendHtmlMail(MailInfo info)throws Exception{
            info.setHost(host);
            info.setFormName(formName);
            info.setFormPassword(password);   //授权码~不一定是密码
            info.setReplayAddress(replayAddress);
    
            Message message = getMessage(info);
            // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
            Multipart mainPart = new MimeMultipart();
            // 创建一个包含HTML内容的MimeBodyPart
            BodyPart html = new MimeBodyPart();
            // 设置HTML内容
            html.setContent(info.getContent(), "text/html; charset=utf-8");
            mainPart.addBodyPart(html);
            // 将MiniMultipart对象设置为邮件内容
            message.setContent(mainPart);
            Transport.send(message);
        }
        private static Message getMessage(MailInfo info) throws Exception{
            final Properties p = System.getProperties() ;
            p.setProperty("mail.smtp.host", info.getHost());
            p.setProperty("mail.smtp.auth", "true");
            p.setProperty("mail.smtp.user", info.getFormName());
            p.setProperty("mail.smtp.pass", info.getFormPassword());
            p.setProperty("mail.smtp.port", "465");
            p.setProperty("mail.smtp.socketFactory.port", "465");
    
            // 根据邮件会话属性和密码验证器构造一个发送邮件的session
            Session session = Session.getInstance(p, new Authenticator(){
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(p.getProperty("mail.smtp.user"),p.getProperty("mail.smtp.pass"));
                }
            });
            //session.setDebug(true);
            Message message = new MimeMessage(session);
            //消息发送的主题
            message.setSubject(info.getSubject());
            //接受消息的人
            message.setReplyTo(InternetAddress.parse(info.getReplayAddress()));
            //消息的发送者
            message.setFrom(new InternetAddress(p.getProperty("mail.smtp.user"),"发件者信息,如姓名"));
            // 创建邮件的接收者地址,并设置到邮件消息中
            message.setRecipients(Message.RecipientType.TO,new InternetAddress().parse(info.getToAddress()));
    
            // 消息发送的时间
            message.setSentDate(new Date());
            return message ;
        }
    }
    

    3.发送结果至相关用户邮箱

    //配置发送邮件
        public  void send(String failName,String lineName,JSONObject jsonObject,Map mailMap) throws Exception{
            //System.out.println("发送邮件");  
            //邮件标题
            String title ="【"+lineName+"监控报警触发】发生接口异常报警";
            //遍历数组打印结果
            String content ="<table border=\"1\" cellspacing=\"0\" cellpadding=\"0\">";
            content+="<tr><td>所属服务</td>";
            content+="<td>用例名称</td>";
            content+="<td>运行结果</td>";
            content+="<td>运行时间</td>";
            content+="<td>错误描述</td></tr>";
            int contentCountLine=0,contentCountTester=0;
            String contentLine=content,contentTester=content;
            for(int i=0;i<jsonObject.getJSONArray("data").size();i++) {
                int caseFailCount = Integer.parseInt((String) jsonObject.getJSONArray("data").getJSONObject(i).get("caseFailCount"));
                int readFailCount = Integer.parseInt((String) jsonObject.getJSONArray("data").getJSONObject(i).get("readFailCount"));
                if(jsonObject.getJSONArray("data").getJSONObject(i).get("failureMessage")!="") {
                    if(!jsonObject.getJSONArray("data").getJSONObject(i).get("failureMessage").equals("当日首次写入文件失败") || 
                            !jsonObject.getJSONArray("data").getJSONObject(i).get("failureMessage").equals("无法读取到最近一次执行结果")) {
                        if(caseFailCount>=3) {
                            contentCountLine++;
                            contentLine+="<tr><td>"+lineName+"</td>";
                            contentLine+="<td>"+jsonObject.getJSONArray("data").getJSONObject(i).get("fileName")+"</td>";
                            contentLine+="<td>"+jsonObject.getJSONArray("data").getJSONObject(i).get("success")+"</td>";
                            contentLine+="<td>"+refFormatNowDate(Long.valueOf(jsonObject.getJSONArray("data").getJSONObject(i).get("timedate")+""))+"</td>";
                            contentLine+="<td>"+jsonObject.getJSONArray("data").getJSONObject(i).get("failureMessage")+"</td></tr>";    
                        }
                        
                    }else {
                        if(readFailCount>=3) {
                            contentCountTester++;
                            contentTester+="<tr><td>"+lineName+"</td>";
                            contentTester+="<td>"+jsonObject.getJSONArray("data").getJSONObject(i).get("fileName")+"</td>";
                            contentTester+="<td>"+jsonObject.getJSONArray("data").getJSONObject(i).get("success")+"</td>";
                            contentTester+="<td>"+refFormatNowDate(Long.valueOf(jsonObject.getJSONArray("data").getJSONObject(i).get("timedate")+""))+"</td>";
                            contentTester+="<td>"+jsonObject.getJSONArray("data").getJSONObject(i).get("failureMessage")+"</td></tr>";  
                        }
                    }
                }
    }
            }
            //判断给各业务线相关人员发送邮件
            if(contentCountLine>0 && failName.equals("caseFail") ) {
                MailInfo infoLine = new MailInfo();
                switch (lineName){
                case "serverline1":
                    infoLine.setToAddress(mailMap.get("serverline1").toString()); //发送对象的邮箱
                    break;
                case "serverline2":
                    infoLine.setToAddress(mailMap.get("serverline2").toString()); //发送对象的邮箱
                    break;
                case "serverline3":
                    infoLine.setToAddress(mailMap.get("serverline3").toString()); //发送对象的邮箱
                    break;
                case "serverline4":
                    infoLine.setToAddress(mailMap.get("serverline4").toString()); //发送对象的邮箱
                    break;
                default:
                    infoLine.setToAddress(mailMap.get("serverline5").toString()); //发送对象的邮箱
                    break;  
                }
                String finalContentLine="<div>"+lineName+"服务有"+contentCountLine+"个接口发生错误</div><br/>"+contentLine+"</table>"; 
                infoLine.setSubject(title);
                infoLine.setContent(finalContentLine);
                int lineExceCount=0;
                while(lineExceCount<2) {
                        try {
                            TimeUnit.SECONDS.sleep(1);
                            SendJavaHtmlEmail.sendHtmlMail(infoLine);
                            lineExceCount=2;
                            } catch (Exception e) {
                                lineExceCount++;
                                if(lineExceCount==2) {
                                    loginfo.info("'"+title+"'的邮件发送失败!,邮件服务无法链接");
                                    e.printStackTrace();
                                }                                       
                            }
                }    
            }
            
            //判断是否要给测试人员发送邮件
            if(contentCountTester>0 && failName.equals("readFail") ) {
                    MailInfo infoTester=new MailInfo();
                    infoTester.setToAddress(mailMap.get("test").toString());
                    String finalContentTester="<div>"+lineName+"服务有"+contentCountTester+"个接口发生错误</div><br/>"+contentTester+"</table>";
                    infoTester.setSubject(title);
                    infoTester.setContent(finalContentTester);
                    int testerExceCount=0;
                    while(testerExceCount<2) {
                         try {
                            TimeUnit.SECONDS.sleep(1);
                            SendJavaHtFmlEmail.sendHtmlMail(infoTester);
                            testerExceCount=2;
                        } catch (Exception e) {
                            testerExceCount++;
                                if(testerExceCount==2) {
                                    loginfo.info("给Tester发送的'"+title+"'的邮件发送失败!,邮件服务无法链接");
                                    e.printStackTrace();
                                }                       
                        }   
                    }
            }
        }
    

    4.其他方法汇总

    // 解析csv文件
        private ArrayList<String[]> read(String filepath) {
            ArrayList<String[]> csvList = new ArrayList<String[]>();
            try {
                File file = new File(filepath);
                FileInputStream fileInput = new FileInputStream(file);
                InputStreamReader isr = new InputStreamReader(fileInput, "utf-8");
                CsvReader csvReader = new CsvReader(isr);
                csvReader.readHeaders();
                while (csvReader.readRecord()) {
                    csvList.add(csvReader.getValues());
                }
                csvReader.close();
                fileInput.close();
                isr.close();        
            } catch (IOException e) {
                e.printStackTrace();
            }
            return csvList;
        }
    
        // 读取当前系统日期
        public String refFormatNowDate(long timeMill) {
            Date nowTime = new Date(timeMill);
            SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String retStrFormatNowDate = sdFormatter.format(nowTime);
            return retStrFormatNowDate;
        }
    
        // 获取当日时间戳
        public String formatTodayDate() {
            Date nowTime = new Date(System.currentTimeMillis());
            SimpleDateFormat tdFormatter = new SimpleDateFormat("yyyyMMdd");
            String formatStrTodayDate = tdFormatter.format(nowTime);
            return formatStrTodayDate;
        }
    

    相关文章

      网友评论

          本文标题:发送邮件浅析

          本文链接:https://www.haomeiwen.com/subject/xbqyuqtx.html