使用javamail发送附件,实践

0. 准备工作

下载javax.mail.jar,加入工程的buildpath里面

1. 创建EmailReport类

package swiftcoder2_0;
import java.util.Properties;


import javax.activation.*;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;




import GL.GL;


public class EmailReport {

/*!
@method     sendReport:
@author     chenchen 2015-11-20  
@description  send the test results to whom should be known
@param      user: the sender
@param      password : the sender's password
@param      toMail: the receivers
*/
public static void sendReport( ){
final String username = "[email protected]";
   final String password = "chenchen2012";


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


   Session session = Session.getInstance(props,
           new javax.mail.Authenticator() {
               protected PasswordAuthentication getPasswordAuthentication() {
                   return new PasswordAuthentication(username, password);
               }
           });
   session.setDebug(true); //有他会打印一些调试信息。  


   try {
    //消息体实例
       Message message = new MimeMessage(session);
       message.setFrom(new InternetAddress(username));
       message.setRecipients(Message.RecipientType.TO,
               InternetAddress.parse("[email protected]"));
       message.setSubject("Testing Subject");
       message.setText("PFA");


       BodyPart messageBodyPart = new MimeBodyPart();
       messageBodyPart.setText("pardon ideas") ;
       
       Multipart multipart = new MimeMultipart();
       multipart.addBodyPart(messageBodyPart);
       
       messageBodyPart = new MimeBodyPart(); 
       String file = "E:/Documents/QA.Management/automation/swiftcoder2_0/test-results/test.txt";
       String fileName = "test.txt";
       DataSource source = new FileDataSource(file);
       messageBodyPart.setDataHandler(new DataHandler(source));
       messageBodyPart.setFileName(fileName);
       
       multipart.addBodyPart(messageBodyPart);


       message.setContent(multipart);


       System.out.println("Sending");


       Transport.send(message);


       System.out.println("Done");


   } catch (MessagingException e) {
       e.printStackTrace();
   }
 
}

public static void sendMail(String fromMail, String user, String password,  
            String toMail,  
            String mailTitle,  
            String mailContent) throws Exception {  
Properties props = new Properties(); //可以加载一个配置文件  
// 使用smtp:简单邮件传输协议  
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", "smtp.exmail.qq.com");//存储发送邮件服务器的信息  
props.put("mail.smtp.auth", "true");//同时通过验证  

Session session = Session.getInstance(props);//根据属性新建一个邮件会话  
session.setDebug(true); //有他会打印一些调试信息。  

MimeMessage message = new MimeMessage(session);//由邮件会话新建一个消息对象  
message.setFrom(new InternetAddress(fromMail));//设置发件人的地址  
message.setRecipient(Message.RecipientType.TO, new InternetAddress(toMail));//设置收件人,并设置其接收类型为TO  
message.setSubject(mailTitle);//设置标题  
//设置信件内容  
//message.setText("Hello", "text/plain"); //发送 纯文本 邮件 todo 
//message.setContent("hello", "text/plain");
//message.setContent(mailContent, "text/html;charset=gbk"); //发送HTML邮件,内容样式比较丰富  
//message.setSentDate(new Date());//设置发信时间  
//message.saveChanges();//存储邮件信息  

//设置正文消息体
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(mailContent);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
//设置附件
messageBodyPart = new MimeBodyPart();
String absolutePath = System.getProperty("user.dir");
absolutePath.replace("\\", "\\\\");
      String file = absolutePath + "\\test-output\\emailable-report.html";
      //String file ="E:\\Documents\\QA.Management\\automation\\swiftcoder2_0\\test-output\\emailable-report.html";
       String fileName = "emailable-report.html";
       DataSource source = new FileDataSource(file);
       messageBodyPart.setDataHandler(new DataHandler(source));
       messageBodyPart.setFileName(fileName);
       multipart.addBodyPart(messageBodyPart);
       message.setContent(multipart);
       
//发送邮件  
Transport transport = session.getTransport("smtp");  

transport.connect("smtp.exmail.qq.com", user, password);  

transport.sendMessage(message, message.getAllRecipients());//发送邮件,其中第二个参数是所有已设好的收件人地址  
transport.close();  
}

public static void main(String args[]) throws Exception{
//sendReport();
sendMail(GL.getString("fromMail"), GL.getString("fromMail") ,GL.getString("pwdFromMail"), "[email protected]", "mail title" , "See the attachment, test results here");

}
}

其中 sendReport sendMail函数都有效。

2. 在用例执行完成后,增加report listener,调用sendMail函数,发送测试结果

2.0 有误的实践

以下代码,本意是想测试套跑完,发送邮件,实际运行结果是,此函数调用在测试套中,所以发送的上一次执行结果,故不是本意图。

@AfterTest
@Configuration(afterTestClass= true, groups = {"test.workflow"})
public void TearDown() throws Exception{
System.out.println("----After Test--------");
//after the run completion, send the test results to people who are concerned about it
String fromMail = GL.getString("fromMail");
String pwdFromMail = GL.getString("pwdFromMail");
String toMail = GL.getString("toMail");
System.out.println(fromMail +"===="  + toMail );

EmailReport.sendMail(fromMail, fromMail, pwdFromMail, toMail, "AutoTest Results from Swiftcoder 2.0.3" , "See the attachment, test results here");
}

2.1 正确的实践

运行测试类增加report listener在测试套跑完,调用发送邮件

2.1.1 增加监听调用

@Listeners({swiftcoder2_0.ReportResult.class})

public class TC_Operation {

@AfterTest
@Configuration(afterTestClass= true, groups = {"test.workflow"})
public void TearDown() throws Exception{
System.out.println("----After Test--------");
}

@Test(groups = {"groupa"}, retryAnalyzer = TestngRetry.class)
public void testa(){
//code here
}

@Test

XXX

@Test

XXXX

}

2.1.2 增加报表监听类

public class ReportResult implements IReporter {
/*!
@method     sendMail:
@author     chenchen 2015-11-20  
@description  send the test results to whom 
@param      fromMail: the sender
@param      user: the sender 
@param      password : the sender's password
@param      toMail: the receivers
@param      mailTitle: mail subject
@param      mailContent: mail body text
*/
public static void sendMail(String fromMail, String user, String password,  
           String toMail,  
           String mailTitle,  
           String mailContent) throws Exception {  

if(mailTitle.equals("") || mailTitle == null){
mailTitle = "No subject";
}
if(mailContent.equals("") || mailContent == null){
mailContent = "No body";
}


Properties props = new Properties(); //可以加载一个配置文件  
// 使用smtp:简单邮件传输协议  
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", "smtp.exmail.qq.com");//存储发送邮件服务器的信息  
props.put("mail.smtp.auth", "true");//同时通过验证  

Session session = Session.getInstance(props);//根据属性新建一个邮件会话  
session.setDebug(true); //有他会打印一些调试信息。  

MimeMessage message = new MimeMessage(session);//由邮件会话新建一个消息对象  
message.setFrom(new InternetAddress(fromMail));//设置发件人的地址  

;
new InternetAddress();
InternetAddress[] toList = InternetAddress.parse(toMail);
message.setRecipients(Message.RecipientType.TO, toList);//设置多个收件人,并设置其接收类型为TO  
//message.setRecipient(Message.RecipientType.TO, new InternetAddress(toMail));//设置收件人,并设置其接收类型为TO  
message.setSubject(mailTitle);//设置标题  
//设置信件内容  
//message.setText("Hello", "text/plain"); //发送 纯文本 邮件 todo 
//message.setContent("hello", "text/plain");
//message.setContent(mailContent, "text/html;charset=gbk"); //发送HTML邮件,内容样式比较丰富  
//message.setSentDate(new Date());//设置发信时间  
//message.saveChanges();//存储邮件信息  

//设置正文消息体
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(mailContent);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
//设置附件
messageBodyPart = new MimeBodyPart();
String absolutePath = System.getProperty("user.dir");
absolutePath.replace("\\", "\\\\");
      String file = absolutePath + "\\test-output\\emailable-report.html";
      //String file ="E:\\Documents\\QA.Management\\automation\\swiftcoder2_0\\test-output\\emailable-report.html";
       String fileName = "emailable-report.html";
       DataSource source = new FileDataSource(file);
       messageBodyPart.setDataHandler(new DataHandler(source));
       messageBodyPart.setFileName(fileName);
       multipart.addBodyPart(messageBodyPart);
       message.setContent(multipart);
       
//发送邮件  
Transport transport = session.getTransport("smtp");  

transport.connect("smtp.exmail.qq.com", user, password);  

transport.sendMessage(message, message.getAllRecipients());//发送邮件,其中第二个参数是所有已设好的收件人地址  
transport.close();  
}


@Override
public void generateReport(List xmlSuites, List suites,
String outputDirectory) {

// TODO Auto-generated method stub
//after the run completion, send the test results to people who are concerned about it
String fromMail = GL.getString("fromMail");
String pwdFromMail = GL.getString("pwdFromMail");
String toMail = GL.getString("toMail");
System.out.println("From Mail: " + fromMail +", To Mail: "  + toMail );
try {
sendMail(fromMail, fromMail, pwdFromMail, toMail, "AutoTest Results from Swiftcoder 2.0.3" , "See the attached, pls");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

参考资料

http://blog.csdn.net/zhoubin_v/article/details/1616044

JavaMail使用教程

http://www.360doc.com/content/14/0306/17/16088576_358273704.shtml 

Java mail api详解

http://tiwson.iteye.com/blog/558992

java mail发送多邮件

你可能感兴趣的:(TestNG)