问题:

公司之前可以通过POP3协议收发邮件,因而在SoapUI中用JavaMail可以读取邮件,后来配置了Office 365,POP3协议端口不再开放,邮件全部读取失败,报login timeout,需要改用EWS(Exchange Web Service)协议。

参考 : http://blog.csdn.net/yangcheng33/article/details/55049629

需要导入此JAR包 : ews-java-api-2.0.jar

import java.net.URI
import java.net.URISyntaxException

import microsoft.exchange.webservices.data.core.*
import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion
import microsoft.exchange.webservices.data.core.enumeration.property.*
import microsoft.exchange.webservices.data.core.enumeration.service.ConflictResolutionMode
import microsoft.exchange.webservices.data.core.service.item.Item
import microsoft.exchange.webservices.data.core.service.schema.AppointmentSchema
import microsoft.exchange.webservices.data.credential.*
import microsoft.exchange.webservices.data.property.complex.MessageBody
import microsoft.exchange.webservices.data.search.*

String contentSubject = "Regarding area"
String emailAddress = "auto.tester@zhang.com"
String password = "Autotest202010"
int maxEmailsGet = 5
String queryString = ""

ExchangeService service = getService(emailAddress, password);

FindItemsResults<Item> findItems = getEmails(maxEmailsGet, queryString, service);

// 迭代 邮件内容
for (Item mail : findItems) {
	String subject = mail.getSubject()
	//log.info "Email subject : "+subject

	MessageBody messageBody = mail.getBody()
	messageBody.setBodyType(BodyType.Text)

	def hasAttachment = mail.getHasAttachments()
	//log.info "Has attatchment ? :"+hasAttachment

	if(subject.contains(contentSubject)&&hasAttachment.equals(true)&&mail.getIsRead().equals(false)){
		assert true,"Check email pass"

		//置email为已读,并且同步到邮件服务器,这样无论以什么方式查看邮件,邮件都是已读状态
		mail.setIsRead(true)
	 	mail.update(ConflictResolutionMode.AlwaysOverwrite)
		break
	}
	
	else if(maxEmailsGet==1){
		assert false,"Check email fail"
	}
	
	maxEmailsGet--
}


// 读取 Inbox下的邮件
public static FindItemsResults<Item> getEmails(int maxEmailsGet, String queryString, ExchangeService service) throws Exception {
	// 默认读取 Inbox下的邮件,最大读取5封
	WellKnownFolderName folderName = WellKnownFolderName.Inbox;
	ItemView itemView = new ItemView(maxEmailsGet);
	FindItemsResults<Item> findItems = service.findItems(folderName, queryString, itemView);

	// 定义基础属性,此步骤必须要,否则会抛异常
	PropertySet detailedPropertySet = new PropertySet(BasePropertySet.FirstClassProperties, AppointmentSchema.Recurrence);
	service.loadPropertiesForItems(findItems, detailedPropertySet);
	return findItems;
}

// 连接服务器
public static ExchangeService getService(String emailAddress, String password) throws URISyntaxException {
	ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
	ExchangeCredentials credentials = new WebCredentials(emailAddress, password);
	service.setUrl(new URI("https://outlook.office365.com/EWS/Exchange.asmx"));
	service.setCredentials(credentials);
	return service;
}