java ews_Java---使用EWS 写个ExchangeMailUtil

依赖包:

commons-httpclient-3.1.jar

commons-codec-1.10.jar

commons-logging-1.2.jar

jcifs-1.3.17.jar

代码示例:

创建MailBean类:

import java.util.Date;

public class MailBean {

public BigDecimal getId() {

return id;

}

public void setId(BigDecimal id) {

this.id = id;

}

public String getTitle() {

return title;

}

public void setTitle(String title) {

this.title = title;

}

public String getFromPeople() {

return fromPeople;

}

public void setFromPeople(String fromPeople) {

this.fromPeople = fromPeople;

}

public String getReceivePeople() {

return receivePeople;

}

public void setReceivePeople(String receivePeople) {

this.receivePeople = receivePeople;

}

public Date getReceiveTime() {

return receiveTime;

}

public void setReceiveTime(Date receiveTime) {

this.receiveTime = receiveTime;

}

public String getReadUrl() {

return readUrl;

}

public void setReadUrl(String readUrl) {

this.readUrl = readUrl;

}

public int getIsRead() {

return isRead;

}

public void setIsRead(int isRead) {

this.isRead = isRead;

}

public String getMailId() {

return mailId;

}

public void setMailId(String mailId) {

this.mailId = mailId;

}

public MailBean() {

}

public MailBean(BigDecimal id,String title, String fromPeople, String receivePeople, Date receiveTime, String mailId,

String readUrl, int isRead) {

this.id=id;

this.title = title;

this.fromPeople = fromPeople;

this.receivePeople = receivePeople;

this.receiveTime = receiveTime;

this.mailId = mailId;

this.readUrl = readUrl;

this.isRead = isRead;

}

private BigDecimal id;

private String title;

private String mailId;

private String fromPeople;

private String receivePeople;

private Date receiveTime;

private String readUrl;

private int isRead;

}

创建ExchangeMailUtil工具类:

import java.net.URI;

import java.net.URISyntaxException;

import java.util.ArrayList;

import java.util.Date;

import java.util.List;

import microsoft.exchange.webservices.data.core.ExchangeService;

import microsoft.exchange.webservices.data.core.PropertySet;

import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;

import microsoft.exchange.webservices.data.core.enumeration.property.BodyType;

import microsoft.exchange.webservices.data.core.enumeration.property.WellKnownFolderName;

import microsoft.exchange.webservices.data.core.enumeration.search.OffsetBasePoint;

import microsoft.exchange.webservices.data.core.enumeration.search.SortDirection;

import microsoft.exchange.webservices.data.core.service.folder.Folder;

import microsoft.exchange.webservices.data.core.service.item.EmailMessage;

import microsoft.exchange.webservices.data.core.service.item.Item;

import microsoft.exchange.webservices.data.core.service.schema.EmailMessageSchema;

import microsoft.exchange.webservices.data.core.service.schema.ItemSchema;

import microsoft.exchange.webservices.data.credential.ExchangeCredentials;

import microsoft.exchange.webservices.data.credential.WebCredentials;

import microsoft.exchange.webservices.data.property.complex.MessageBody;

import microsoft.exchange.webservices.data.search.FindItemsResults;

import microsoft.exchange.webservices.data.search.ItemView;

import microsoft.exchange.webservices.data.search.filter.SearchFilter;

/**

Exchange邮件服务工具类

*/

public class ExchangeMailUtil {

private String mailServer;

private String user;

private String password;

private String domain;

// 自定义一个邮件前缀

private String readUrlPrefix;

public ExchangeMailUtil() {

}

public ExchangeMailUtil(String mailServer, String user, String password, String readUrlPrefix) {

this.mailServer = mailServer;

this.user = user;

this.password = password;

this.readUrlPrefix = readUrlPrefix;

}

public List getUserUnReadMail() throws Exception {

// Outlook Web Access路径通常为/EWS/exchange.asmx

List list = new ArrayList<>();

// 接收邮件

// 原本的读取全部,改为读取“未读”

// ArrayList mails = this.receive(20);

// 不要停下来啊,我这里就写死20邮件了,做分页的交给你了(提示ItemView)

SearchFilter searchFilter = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false);

ArrayList mails = this.receive(20, searchFilter);

for (EmailMessage mail : mails) {

if (mail.getIsRead())

continue;

String title = mail.getSubject();

Date receiveTime = mail.getDateTimeReceived();

String fromPeople = mail.getFrom().getName();

String receivePeople = mail.getReceivedBy().getName();

String id = mail.getRootItemId().toString();

int index = id.indexOf("AAAAA");

String readUrl = readUrlPrefix + id.substring(index + 2, id.length() - 1) + "A";

MailBean mailBean = new MailBean(null, title, fromPeople, receivePeople, receiveTime, id, readUrl, 0);

list.add(mailBean);

}

return list;

}

public List getUserUnReadMailPage(int start, int limit) throws Exception {

// Outlook Web Access路径通常为/EWS/exchange.asmx

List list = new ArrayList<>();

// 接收邮件

// ArrayList mails = this.receive(20);

// 原本的读取全部,改为读取“未读”

SearchFilter searchFilter = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, true);

// 循环获取邮箱邮件

ItemView view = new ItemView(limit, (start - 1) * limit, OffsetBasePoint.Beginning);

// 按照时间顺序收取

view.getOrderBy().add(ItemSchema.DateTimeReceived, SortDirection.Descending);

ArrayList mails = this.receive(20, searchFilter, view);

for (EmailMessage mail : mails) {

if (mail.getIsRead())

continue;

String title = mail.getSubject();

Date receiveTime = mail.getDateTimeReceived();

String fromPeople = mail.getFrom().getName();

String receivePeople = mail.getReceivedBy().getName();

String id = mail.getRootItemId().toString();

int index = id.indexOf("AAAAA");

String readUrl = readUrlPrefix + id.substring(index + 2, id.length() - 1) + "A";

MailBean mailBean = new MailBean(null, title, fromPeople, receivePeople, receiveTime, id, readUrl, 0);

list.add(mailBean);

}

return list;

}

/**

* 创建邮件服务

*

* @return 邮件服务

*/

public ExchangeService getExchangeService() {

ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);

// 用户认证信息

ExchangeCredentials credentials;

if (domain == null) {

credentials = new WebCredentials(user, password);

} else {

credentials = new WebCredentials(user, password, domain);

}

service.setCredentials(credentials);

try {

service.setUrl(new URI(mailServer));

} catch (URISyntaxException e) {

e.printStackTrace();

}

return service;

}

/**

* 收取邮件

*

* @param max

* 最大收取邮件数

* @param searchFilter

* 收取邮件过滤规则

* @return

* @throws Exception

*/

public ArrayList receive(int max, SearchFilter searchFilter) throws Exception {

ArrayList result = new ArrayList<>();

try {

System.out.println(user + "," + password + "," + mailServer);

ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);

ExchangeCredentials credentials = new WebCredentials(user, password);

service.setCredentials(credentials);

service.setUrl(new URI(mailServer));

// 绑定收件箱,同样可以绑定发件箱

Folder inbox = Folder.bind(service, WellKnownFolderName.Inbox);

// 获取文件总数量

int count = inbox.getTotalCount();

// 没有邮件直接返回

if (count == 0)

return result;

if (max > 0) {

count = count > max ? max : count;

}

// 循环获取邮箱邮件

ItemView view = new ItemView(count);

// 按照时间顺序收取

view.getOrderBy().add(ItemSchema.DateTimeReceived, SortDirection.Descending);

FindItemsResults findResults;

if (searchFilter == null) {

findResults = service.findItems(inbox.getId(), view);

} else {

findResults = service.findItems(inbox.getId(), searchFilter, view);

}

service.loadPropertiesForItems(findResults, PropertySet.FirstClassProperties);

for (Item item : findResults.getItems()) {

EmailMessage message = (EmailMessage) item;

result.add(message);

}

} catch (Exception e) {

// TODO: handle exception

e.printStackTrace();

throw e;

}

return result;

}

/**

* 收取邮件

*

* @param max

* 最大收取邮件数

* @param searchFilter

* 收取邮件过滤规则

* @return

* @throws Exception

*/

public ArrayList receive(int max, SearchFilter searchFilter, ItemView itemView) throws Exception {

ArrayList result = new ArrayList<>();

try {

System.out.println(user + "," + password + "," + mailServer);

ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);

ExchangeCredentials credentials = new WebCredentials(user, password);

service.setCredentials(credentials);

service.setUrl(new URI(mailServer));

// 绑定收件箱,同样可以绑定发件箱

Folder inbox = Folder.bind(service, WellKnownFolderName.Inbox);

// 获取文件总数量

int count = inbox.getTotalCount();

// 没有邮件直接返回

if (count == 0)

return result;

if (max > 0) {

count = count > max ? max : count;

}

/*

* // 循环获取邮箱邮件 ItemView view = new ItemView(count); // 按照时间顺序收取

* view.getOrderBy().add(ItemSchema.DateTimeReceived,

* SortDirection.Descending);

*/

FindItemsResults findResults;

if (searchFilter == null) {

findResults = service.findItems(inbox.getId(), itemView);

} else {

findResults = service.findItems(inbox.getId(), searchFilter, itemView);

}

if (findResults.isMoreAvailable())

service.loadPropertiesForItems(findResults, PropertySet.FirstClassProperties);

for (Item item : findResults.getItems()) {

EmailMessage message = (EmailMessage) item;

result.add(message);

}

} catch (Exception e) {

// TODO: handle exception

e.printStackTrace();

throw e;

}

return result;

}

/**

* 收取所有邮件

*

* @throws Exception

*/

public ArrayList receive(int max) throws Exception {

return receive(max, null);

}

/**

* 收取邮件

*

* @throws Exception

*/

public ArrayList receive() throws Exception {

return receive(0, null);

}

/**

* 发送带附件的mail

*

* @param subject

* 邮件标题

* @param to

* 收件人列表

* @param cc

* 抄送人列表

* @param bodyText

* 邮件内容

* @param attachmentPaths

* 附件地址列表

* @throws Exception

*/

public void send(String subject, String[] to, String[] cc, String bodyText, String[] attachmentPaths)

throws Exception {

ExchangeService service = getExchangeService();

EmailMessage msg = new EmailMessage(service);

msg.setSubject(subject);

MessageBody body = MessageBody.getMessageBodyFromText(bodyText);

body.setBodyType(BodyType.HTML);

msg.setBody(body);

for (String toPerson : to) {

msg.getToRecipients().add(toPerson);

}

if (cc != null) {

for (String ccPerson : cc) {

msg.getCcRecipients().add(ccPerson);

}

}

if (attachmentPaths != null) {

for (String attachmentPath : attachmentPaths) {

msg.getAttachments().addFileAttachment(attachmentPath);

}

}

msg.send();

}

/**

* 发送不带附件的mail

*

* @param subject

* 邮件标题

* @param to

* 收件人列表

* @param cc

* 抄送人列表

* @param bodyText

* 邮件内容

* @throws Exception

*/

public void send(String subject, String[] to, String[] cc, String bodyText) throws Exception {

send(subject, to, cc, bodyText, null);

}

public int getUnreadCount() throws Exception {

int unreadCount = 0;

ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);

ExchangeCredentials credentials = new WebCredentials(user, password);

service.setCredentials(credentials);

service.setUrl(new URI(mailServer));

// 绑定收件箱,同样可以绑定发件箱

Folder inbox = Folder.bind(service, WellKnownFolderName.Inbox);

unreadCount = inbox.getUnreadCount();

return unreadCount;

}

}

关于如何使用EWS JAVA API读取exchange邮件看下篇:

https://www.cnblogs.com/itczybk/articles/11012107.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/395821.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Ilya Muromets(DP or 思维)

Ilya Muromets Gym - 100513F Силачом слыву недаром — семерых одним ударом!From the Russian cartoon on the German fairy tale.Ilya Muromets is a legendary bogatyr. Right now he is struggling against Zmej Gorynych, a drago…

C# 装箱和拆箱

C#的值类型可以分为在栈上分配内存的值类型和在托管堆上分配内存的引用类型。 1、那么值类型和引用类型能否相互转换呢? 答案是肯定的,C#通过装箱和拆箱来实现两者的相互转换。 (1)、装箱 ---把值类型强制转换成引用类型(object类型) (2)、拆箱 ---把引用类型强制转换成值…

第五章

学会了开发板测试环境的调试和烧写android系统。 学到的知识&#xff1a; 一、安装串口调试工具:minicom 第1步&#xff1a;检测当前系统是否支持USB转串口。 # lsmod | grep usbserial 第2步&#xff1a;安装minicom # qpt-get install minicom 第3步:配置minicom # minicom -…

Angular的后院:组件依赖关系的解决

by Dor Moshe通过Dor Moshe Angular的后院&#xff1a;解决 组件依赖关系 (Angular’s Backyard: The Resolving of Components Dependencies) This article originally appeared on dormoshe.io这篇文章 最初出现在dormoshe.io Many of us use the Hierarchical Dependenc…

node中的Stream-Readable和Writeable解读

在node中&#xff0c;只要涉及到文件IO的场景一般都会涉及到一个类&#xff0d;Stream。Stream是对IO设备的抽象表示&#xff0c;其在JAVA中也有涉及&#xff0c;主要体现在四个类&#xff0d;InputStream、Reader、OutputStream、Writer&#xff0c;其中InputStream和OutputSt…

新Rider预览版发布,对F#的支持是亮点

JetBrains一直在改进自己的跨平台.NET IDE产品Rider&#xff0c;努力使其成为Visual Studio家族产品可承担职能的重要替代者。于今年四月发布的Rider预览版&#xff08;EAP 21&#xff09;提供了一些新特性&#xff0c;其中的亮点在于对函数式编程语言F#的支持。\\鉴于这是Ride…

java代码整合_java合并多个文件的实例代码

在实际项目中&#xff0c;在处理较大的文件时&#xff0c;常常将文件拆分为多个子文件进行处理&#xff0c;最后再合并这些子文件。下面就为各位介绍下Java中合并多个文件的方法。Java中合并子文件最容易想到的就是利用BufferedStream进行读写。具体的实现方式如下&#xff0c;…

正则表达式的一些规则

1.限定修饰符只对其紧前的元字符有效 String rex8 "\\d\\D"; 上式中&#xff0c;只对\\D有效&#xff0c;即有至少有1个&#xff08;1个或多个&#xff09;非数字&#xff0c;\\d仍然只许有一个数字。 2.[1,2,3]和[123]是一样的转载于:https://www.cnblogs.com/Sabr…

2016版单词的减法_在2016年最大的电影中,女性只说了27%的单词。

2016版单词的减法by Amber Thomas通过琥珀托马斯 在2016年最大的电影中&#xff0c;女性只说了27&#xff05;的单词。 (Women only said 27% of the words in 2016’s biggest movies.) Movie trailers in 2016 promised viewers so many strong female characters. Jyn Erso…

软件工程博客---团队项目---个人设计2(算法)

针对分析我们团队项目的需求&#xff0c;我们选定Dijkstra算法。 算法的基本思想&#xff1a; Dijkstra算法是由E.W.Dijkstra于1959年提出&#xff0c;又叫迪杰斯特拉算法&#xff0c;它应用了贪心算法模式&#xff0c;是目前公认的最好的求解最短路径的方法。算法解决的是有向…

UWP 杂记

UWP用选取文件对话框 http://blog.csdn.net/u011033906/article/details/65448394 文件选取器、获取文件属性、写入和读取、保存读取和删除应用数据 https://yq.aliyun.com/articles/839 UWP判断文件是否存在 http://blog.csdn.net/lindexi_gd/article/details/51387901…

微信上传素材 java_微信素材上传(JAVA)

public String uploadMaterial(String url,InputStream sbs,String filelength,String filename, String type) throws Exception {try {DataInputStream innew DataInputStream(sbs);url url.replace("TYPE", type);URL urlObj new URL(url);// 创建Http连接HttpU…

SQL Server读写分离之发布订阅

一、发布 上面有多种发布方式&#xff0c;这里我选择事物发布&#xff0c;具体区别请自行百度。 点击下一步、然后继续选择需要发布的对象。 如果需要筛选发布的数据点击添加。 根据自己的计划选择发布的时间。 点击安全设置&#xff0c;设置代理信息。 最后单击完成系统会自动…

码农和程序员的几个重要区别!

如果一个企业老板大声嚷嚷说&#xff0c;“我要招个程序员”&#xff0c;那么十之八九指的是“码农”——一种纯粹为了钱而写代码的技术人员。这其实是一种非常狭隘和错误的做法&#xff0c;原因么&#xff0c;且听我一一道来。1、码农写代码&#xff0c;程序员写系统从本质上讲…

sql server2008禁用远程连接

1.打开SQL Server 配置管理器&#xff0c;双击左边 SQL Server 网络配置&#xff0c;点击TCP/IP协议,在协议一栏中,找到 全部侦听,修改为否&#xff0c;然后点击IP地址,将IP地址为127.0.0.1(IPV4)或::1(IPV6)的已启用修改为是,其它的IP地址的已启用修改为否 注意&#xff1a;如…

snapchat注册不到_从Snapchat获得开发人员职位中学到的经验教训

snapchat注册不到Here are three links worth your time:这是三个值得您花费时间的链接&#xff1a; I just got a developer job at Snapchat. Here’s what I learned and how it can help you with your job search (15 minute read) 我刚刚在Snapchat获得开发人员职位。 这…

java bitmap jar_Java面试中常用的BitMap代码

引言阿里内推面试的时候被考了一道编程题&#xff1a;10亿个范围为1~2048的整数&#xff0c;将其去重并计算数字数目。我看到这个题目就想起来了《编程珠玑》第一章讲的叫做BitMap的数据结构&#xff0c;但是我并没有在java上实现过&#xff0c;这就比较尴尬了&#xff0c;再加…

移动端工程架构与后端工程架构的思想摩擦之旅(1)

此文已由作者黎星授权网易云社区发布。欢迎访问网易云社区&#xff0c;了解更多网易技术产品运营经验记资源投放后端工程的架构调整与优化 架构思考一直以来对软件工程架构有着极大的兴趣&#xff0c;无论是之前负责的移动端Android工程&#xff0c;亦或是现在转到后端开发后维…

View野指针问题分析报告

【问题描述】 音乐组同事反馈了一个必现Native Crash问题&#xff0c;tombstone如下&#xff1a; pid: 5028, tid: 5028, name: com.miui.player >>> com.miui.player <<< signal 11 (SIGSEGV), code 2 (SEGV_ACCERR), fault addr 79801f28r0 7ac59c98 r1 …

SicilyFunny Game

一、题目描述 Two players, Singa and Suny, play, starting with two natural numbers. Singa, the first player, subtracts any positive multiple of the lesser of the two numbers from the greater of the two numbers, provided that the resulting number must be non…