美文网首页
发送邮件浅析

发送邮件浅析

作者: 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;
    }

相关文章

  • 发送邮件浅析

    1.编写javabean,MailInfo.class 2.配置邮件的发送发和接收方的信息 3.发送结果至相关用户...

  • spring boot 邮件发送基础详解(4种邮件超级详细)

    本文将介绍spring boot邮件发送将介绍以下几个方面: 邮件使用场景 邮件发送原理 邮件发送流程 邮件发送步...

  • SKPSMTPMessage

    SKPSMTPMessage 可以自己实现邮件发送,采用系统的邮件发送会弹出邮件发送框,如果要求静默发送邮件可参照...

  • SpringBoot 发送邮件

    # 依赖 # 配置 # 发送简单文本邮件 # 发送html邮件 # 使用邮件模板发送邮件 添加依赖 配置 新建ht...

  • 2018-10-11

    文本邮件的发送 1.邮件发送流程 ​ 邮件的发送是主动行为:主要通过 MUA/邮件客户端软件,将邮件内容发送给对应...

  • python自动发送邮件

    python自动发送邮件 在说python发送邮件之前,需要了解一下简单的邮件发送知识,邮件发送一般通过SMTP协...

  • python -- Email , send(smtp), re

    python Email功能: 发送普通文本邮件 发送带有html格式的邮件 发送带有附件的邮件 发送插入图片到正...

  • 2018-07-02

    发送邮件 //发送邮件 @ResponseBody @RequestMapping("email") public...

  • Golang使用SMTP发送邮件

    使用SMTP发送邮件 发送邮件测试 邮箱如下

  • python学习(21)smtp发送邮件

    本文介绍python发送邮件模块smtplib以及相关MIME模块。smtplib用于生成邮件发送的代理,发送邮件...

网友评论

      本文标题:发送邮件浅析

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