依赖包:

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<EmailMessage> mails = this.receive(20);
// 不要停下来啊,我这里就写死20邮件了,做分页的交给你了(提示ItemView)
SearchFilter searchFilter = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false);
ArrayList<EmailMessage> 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<EmailMessage> 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<EmailMessage> 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<EmailMessage> receive(int max, SearchFilter searchFilter) throws Exception {
ArrayList<EmailMessage> 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<Item> 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<EmailMessage> receive(int max, SearchFilter searchFilter, ItemView itemView) throws Exception {
ArrayList<EmailMessage> 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<Item> 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<EmailMessage> receive(int max) throws Exception {
return receive(max, null);
} /**
* 收取邮件
*
* @throws Exception
*/
public ArrayList<EmailMessage> 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

最新文章

  1. MySQL5.6安装步骤
  2. c语言语系的命名风格和java系命名风格
  3. php基础复习(一)smarty模板
  4. SPOJ 416 Divisibility by 15 细节题
  5. svn 上传 过滤
  6. yii2 验证码的使用
  7. Apache服务器处理404错误页面技巧
  8. Racing Car Computer dp
  9. Linux学习之CentOS(十七)-----释放 Linux 系统预留的硬盘空间 与Linux磁盘空间被未知资源耗尽 (转)
  10. 0~5年一个Java程序员的晋升之路
  11. Node.js_express_中间件 middleware_登录/注册实例源代码
  12. XRecyclerView上拉刷新下拉加载
  13. Centos7 环境下 Python2.7 换成 Python3.7 运行 scrapy 应用所遇到的问题记录
  14. centOS7.10 KDE桌面字体设置推荐
  15. P3810 【模板】三维偏序(陌上花开)
  16. jQuery中异步请求
  17. WIN7 系统 右键计算机 点击管理 出现对话框:找不到文件。
  18. Metasploit 一些重要模块使用介绍
  19. spring入门(Ioc的理解)
  20. mysql 修改max_connections

热门文章

  1. WPF 3D中多个模型如何设置某一个在最前?
  2. 零元学Expression Design 4 - Chapter 3 看小光被包围了!!如何活用「Text On Path」设计效果
  3. python 教程 第三章、 运算符与表达式
  4. Spring综合Struts2
  5. 让你的sublime text写C代码 (sublime text 2 配置构建C开发环境)
  6. linux_无秘登录问题(不生效)
  7. WPF - Group分组对ListBox等列表样式的约束
  8. WPF 4 单词拼写检查(SpellCheck)
  9. C# WebApi使用AttributeRoutes特性路由
  10. 获取控件中应用的模版的内部的控件,使用LoadContent()方法获取模版跟节点