0. EWS JAVA API是什么?
用来访问 Exchange Web 服务的 Java 客户端,说白了就是一套访问Exchange邮件服务的Java API库,利用它我们可以编写Java代码来动态创建和发送所需要的html邮件了。
1. 如何监听是否有新邮件?
第一步:建立一个Maven项目,加入以下依赖:
<dependency>
<groupId>com.microsoft.ews-java-api</groupId>
<artifactId>ews-java-api</artifactId>
<version>2.0</version>
</dependency>
第二步:通过使用EWS JAVA API访问EWS
要使用EWS JAVA API访问Exchange Web服务(EWS),只需要一个ExchangeService类的实例,如以下示例所示。
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
ExchangeCredentials credentials = new WebCredentials("emailAddress", "password");
service.setCredentials(credentials);
第三步:在EWS JAVA API中使用拉取通知,利用Timer循环运行:
例子里每30秒运行一次拉取操作
List<FolderId> folder = new ArrayList<FolderId>();
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);
}
2. 运行效果
发了三封邮件,邮件的Subject分别是Re: Subject1;Re: Subject2;Re: Subject3
可以看到确实拉取到了新邮件内容,实际效果如下:
图片.png
网友评论