單元測試工具(連載5)

  • 2019 年 12 月 12 日
  • 筆記

1.8 使用JAVA腳本發送測試報告

測試報告產生了,為了配合CI的實現,可以用JAVA來實現發送測試報告到相關人員的郵件系統中,程式碼如下。

案例3:利用JAVA發送電子郵件。

package Util.com.jerry;

import java.io.File;

import java.util.ArrayList;

import java.util.Date;

import java.util.List;

import java.util.Properties;

import javax.activation.DataHandler;

import javax.activation.FileDataSource;

import javax.mail.AuthenticationFailedException;

import javax.mail.Authenticator;

import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.Multipart;

import javax.mail.PasswordAuthentication;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeBodyPart;

import javax.mail.internet.MimeMessage;

import javax.mail.internet.MimeMultipart;

import javax.mail.internet.MimeUtility;

import org.apache.commons.lang.StringUtils;

import org.apache.log4j.LogManager;

import org.apache.log4j.Logger;

/**

* 實現郵件發送功能

* @authorAdministrator

*

*/

public class EmailSender {

privatestatic final Logger logger = LogManager.getLogger(EmailSender.class);

privateString host; // 伺服器地址

privateString from; // 發件人

privateString to; // 收件人 多個收件人以,分隔

privateString title; // 主題

privateString content; // 內容

privateList<File> attachmentlist ; //附件集

privateString username; // 用戶名

privateString password; // 密碼

/**發件人員工編號*/

privateString sendEmployeeId;

publicString getSendEmployeeId() {

returnsendEmployeeId;

}

publicvoid setSendEmployeeId(String sendEmployeeId) {

this.sendEmployeeId= sendEmployeeId;

}

publicString getHost() {

returnhost;

}

publicvoid setHost(String host) {

this.host= host;

}

publicString getFrom() {

returnfrom;

}

publicvoid setFrom(String from) {

this.from= from;

}

publicString getTo() {

returnto;

}

publicvoid setTo(String to) {

this.to= to;

}

publicString getTitle() {

returntitle;

}

publicvoid setTitle(String title) {

this.title= title;

}

publicString getContent() {

returncontent;

}

publicvoid setContent(String content) {

this.content= content;

}

publicList<File> getAttachmentlist() {

returnattachmentlist;

}

publicvoid setAttachmentlist(List<File> attachmentlist) {

this.attachmentlist= attachmentlist;

}

publicString getUsername() {

returnusername;

}

publicvoid setUsername(String username) {

this.username= username;

}

publicString getPassword() {

returnpassword;

}

publicvoid setPassword(String password) {

this.password= password;

}

publicString getPort() {

returnport;

}

publicvoid setPort(String port) {

this.port= port;

}

privateString port;

publicEmailSender(String host, String from, String to, String title,

Stringcontent, List attachmentlist, String username, String password,String port) {

this.host= host;

this.from= from;

this.to= to;

this.title= title;

this.content= content;

this.attachmentlist= attachmentlist;

this.username= username;

this.password= password;

this.port=port;

}

publicEmailSender(String to, String title,

Stringcontent, List attachmentlist) {

this.to= to;

this.title= title;

this.content= content;

this.attachmentlist= attachmentlist;

}

/**

* 發送郵件

* @return 發送狀態資訊index0:狀態 0成功 1失敗;index1:描述錯誤資訊

*/

publicString[] sendMail(){

String[]result=new String[2];

Sessionsession=null;

Propertiesprops = System.getProperties();

props.put("mail.smtp.host",host);

props.put("mail.smtp.sendpartial","true");

props.put("mail.smtp.port",port);

if(StringUtils.isBlank(username)){//不需要驗證用戶名密碼

session= Session.getDefaultInstance(props, null);

}else{

props.put("mail.smtp.auth","true");

EmailAuthenticatorauth = new EmailAuthenticator(username, password);

session= Session.getInstance(props, auth);

}

//設置郵件發送資訊

try{

//創建郵件

MimeMessagemessage = new MimeMessage(session);

//設置發件人地址

message.setFrom(newInternetAddress(from));

//設置收件人地址(多個郵件地址)

InternetAddress[]toAddr = InternetAddress.parse(to);

message.addRecipients(Message.RecipientType.TO,toAddr);

//設置郵件主題

message.setSubject(title);

//設置發送時間

message.setSentDate(newDate());

//設置發送內容

Multipartmultipart = new MimeMultipart();

MimeBodyPartcontentPart = new MimeBodyPart();

contentPart.setText(content);

multipart.addBodyPart(contentPart);

//設置附件

if(attachmentlist!=null&& attachmentlist.size()>0){

for(inti = 0 ; i < attachmentlist.size();i++){

MimeBodyPartattachmentPart = new MimeBodyPart();

FileDataSourcesource = new FileDataSource(attachmentlist.get(i));

attachmentPart.setDataHandler(newDataHandler(source));

attachmentPart.setFileName(MimeUtility.encodeWord(attachmentlist.get(i).getName(),"gb2312", null));

multipart.addBodyPart(attachmentPart);

}

}

message.setContent(multipart);

//登錄SMTP伺服器

if(StringUtils.isBlank(username)) {

//不需驗證

Transport.send(message);

}else {

//需要驗證

Transporttransport = session.getTransport("smtp");

transport.connect();

transport.sendMessage(message,message.getAllRecipients());

transport.close();

}

result[0]="0";

result[1]="發送成功";

logger.info("郵件發送成功!發送人:"+from);

}catch(MessagingExceptionmex){

result[0]="1";

result[1]="郵件伺服器發生錯誤";

if(mexinstanceof AuthenticationFailedException){

result[1]="用戶名或密碼錯誤";

}

}catch (Exception e) {

result[0]="1";

result[1]="系統異常";

}

returnresult;

}

publicstatic void main(String[] args){

StringSNMPTServer = "smtp.126.com";

Stringfrom="[email protected]";

Stringto="[email protected]";

Stringtitle="發送測試報告";

Stringcontent="附件為測試報告";

Stringusername="[email protected]";

Stringpassword="123456";

Stringport="25";

Listlist=new ArrayList();

list.add(newFile("C:\myjava\web\junit.rar"));#junit.rar為發送測試報告的目錄壓縮jar包

EmailSendersender=newEmailSender(SNMPTServer,from,to,title,content,list,username,password,port);

String[] result = sender.sendMail();

System.out.println(result[1]+"ffffffffffffffff");

}

}

/**

* classMyAuthenticator用於郵件伺服器認證 構造器需要用戶名、密碼作參數

*/

class EmailAuthenticator extends Authenticator {

privateString username = null;

privateString password = null;

publicEmailAuthenticator(String username, String password) {

this.username= username;

this.password= password;

}

publicPasswordAuthentication getPasswordAuthentication() {

returnnew PasswordAuthentication(username, password);

}

}

讀者只要修改main()方法開始部分的設置就可以了。

星雲測試

http://www.teststars.cc

奇林軟體

http://www.kylinpet.com

聯合通測

http://www.quicktesting.net