本篇文章是利用Exchange协议来获取已发送邮件的内容。 1.依赖:
<!--Exchange的api接口依赖-->
<dependency>
<groupId>com.microsoft.ews-java-api</groupId>
<artifactId>ews-java-api</artifactId>
<version>2.0</version>
</dependency>
<!--slf4j-api-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.32</version>
</dependency>
2.具体代码:
public class EWSUtils {
private static Logger log = LoggerFactory.getLogger(EWSUtils.class);
public static ExchangeService getExchangeService(String username, String password, String domain) throws Exception {
log.info("Begin to connect to server " + username);
ExchangeService exService = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
ExchangeCredentials credentials = new WebCredentials(username, password);
exService.setCredentials(credentials);
exService.setUrl(new URI("https://" + domain + "/ews/Exchange.asmx"));
return exService;
}
public static boolean readMailByEWS(
String username,
String password,
String domain,
int viewCount,
Date beginDate,
Date endDate
) throws Exception {
ExchangeService exService = getExchangeService(username, password, domain);
Folder inbox = Folder.bind(exService, WellKnownFolderName.Inbox);
ItemView view = new ItemView(viewCount);
view.getOrderBy().add(ItemSchema.DateTimeReceived, SortDirection.Descending);
view.setPropertySet(new PropertySet(ItemSchema.DateTimeReceived));
SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(
LogicalOperator.And,
new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, beginDate),
new SearchFilter.IsLessThanOrEqualTo(ItemSchema.DateTimeReceived, endDate)
);
FindItemsResults<Item> findResults = exService.findItems(inbox.getId(), searchFilter, view);
if (findResults != null && findResults.getTotalCount() > 0) {
exService.loadPropertiesForItems(findResults, PropertySet.FirstClassProperties);
for (Item item : findResults.getItems()) {
EmailMessage msg = EmailMessage.bind(exService, item.getId());
System.out.println("邮件内容 :" + msg.getBody());
}
}
throw new Exception("邮件正文找不到!");
}
}
|