selenium webdriver2.0实现邮件发送

来源:互联网 发布:济南公交 大数据 编辑:程序博客网 时间:2024/05/18 00:11

To send the results I’m using JavaMail 1.4.2.

步骤一:权限验证

              Properties props = new Properties();
              props.put("mail.smtp.auth", true);
              props.put("mail.smtp.starttls.enable", true);
              props.put("mail.smtp.host", "smtp.qq.com");
              props.put("mail.smtp.port", "25");

              Session session = Session.getInstance(props,
                     new javax.mail.Authenticator() {
                              protected PasswordAuthentication getPasswordAuthentication() {
                              return new PasswordAuthentication(username, password);
                    }
                });

步骤二:附件上传

(1)首先创建一个MimeMessage message = new MimeMessage(session);

(2)其次,添加附件(可以是单个文件、也可以为文件夹)
            MimeBodyPart attachFilePart = new MimeBodyPart();
            FileDataSource fds = new FileDataSource(attach);
            attachFilePart.setDataHandler(new DataHandler(fds));
            attachFilePart.setFileName(MimeUtility.encodeWord(fds.getName()));//解决附件名称乱码
            MimeBodyPart textPart = new MimeBodyPart();
            textPart.setContent(attachFilePart, "text/html;charset=UTF-8");
            Multipart mp = new MimeMultipart();
            mp.addBodyPart(attachFilePart);
            File dir = new File(filePath);
            String[] children = dir.list();
            if(children==null){
                System.out.println("dir does not exist");
            }else{
                for(int i=0;i<children.length;i++){
                    String filename = children[i];
                    System.out.println("Adding: " + filename);
                    attachFilePart = new MimeBodyPart();
                    fds = new FileDataSource(filePath+"\\"+filename);
                    attachFilePart.setDataHandler(new DataHandler(fds));
                    attachFilePart.setFileName(MimeUtility.encodeWord(fds.getName()));
                    mp.addBodyPart(attachFilePart);
                }
            }
            message.setContent(mp);
            message.saveChanges();

步骤三,发送邮件

            Transport.send(message, message.getAllRecipients());
            System.out.println("Mail was sent to: " + aToEmailAddr + ", " + aToEmailAddr2 + ", " + aToEmailAddr3);

最后,主函数中调用

           public static void main(String[] args) throws Exception{
                   String sub="邮件并发测试";
                   String from = "***@qq.com";
                   String to1 = "***@gmail.com";
                   String to2 = "***@163.com";
                   String to3 = "***@163.com";
                   String path = "D:\\emailable-report.html";
                   String file="D:\\test";
                   sendEmail(sub, from, to1, to2, to3, path, file);
            }

完整代码链接:http://pan.baidu.com/s/1bnN3VXl

0 0
原创粉丝点击