com.microsoft.ews-java-api
ews-java-api
2.0
- 什么是EWS JAVA API?它是一种用于访问Exchange Web服务的Java客户端。简单来说,它是一个用于访问Exchange邮件服务的Java API库,可以使用它来编写Java代码来动态创建和发送所需的HTML邮件。EWS JAVA API的官方开源代码Git库地址如下:
- 如何监听是否有新邮件?
第一步:创建一个Maven项目,并添加以下依赖项:
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
ExchangeCredentials credentials = new WebCredentials("emailAddress", "password");
service.setCredentials(credentials);
List folder = new ArrayList();
FolderId folder1 = new FolderId(WellKnownFolderName.Inbox);
folder.add(folder1);
final PullSubscription subscription = service.subscribeToPullNotifications(folder, 5, null,
EventType.NewMail, EventType.Created, EventType.Deleted);
Integer cacheTime = 1000 * 30;
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
try {
GetEventsResults events = subscription.getEvents();
System.out.println("####### EVENTS: " + events.getItemEvents().toString());
for (ItemEvent itemEvent : events.getItemEvents()) {
if (itemEvent.getEventType() == EventType.NewMail) {
EmailMessage message = EmailMessage.bind(service, itemEvent.getItemId());
System.out.println("######## NEW EMAIL MESSAGE IS: " + message.getSubject());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, 0, cacheTime);
}
第二步:使用EWS JAVA API访问EWS
要访问Exchange Web服务(EWS)并使用EWS JAVA API,只需创建一个ExchangeService类的实例,如下所示的示例代码:
第三步:使用拉取通知在EWS JAVA API中进行轮询
可以使用Timer来循环运行拉取操作,以下是一个示例代码,每30秒运行一次拉取操作:
- 运行效果
发送了三封邮件,主题分别为Re: Subject1、Re: Subject2和Re: Subject3。可以看到成功拉取到了新邮件的内容,实际效果如下所示:
{图片.png}