使用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<XmlSuite> xmlSuites, List<ISuite> 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發送多郵件

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章