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<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
Java---使用EWS 写个ExchangeMailUtil的更多相关文章
- c++ c# java 调用 c++ 写的dll
1. vs 中新建win32 dll 项目 testdll 添加实现文件 test.cpp #include "stdafx.h" #include <ios ...
- 对着java并发包写.net并发包之原子类型实现
众所周知,java1.5并发包通过volatile+CAS原理提供了优雅的并发支持.今天仔细想想.net也有volatile关键字保证内存的可见性,同时也有Interlocked提供了CAS的API, ...
- Java自己动手写连接池四
Java自己动手写连接池四 测试: package com.kama.cn; import java.sql.Connection; public class Test { public static ...
- Java自己动手写连接池三
Java自己动手写连接池三,核心代码; package com.kama.cn; import java.sql.Connection;import java.util.ArrayList;impor ...
- Java将数据写进excel
Java将数据写进excel Java将数据写进excel class User { private String name ; private String password; public Use ...
- 【转载】java调用C++写的DLL
用java调用C++写的DLL一直以来都是一个比较麻烦但又很常见的问题. 我们知道,使用 JNI 调用 .dll/.so 共享类库是非常非常麻烦和痛苦的. 如果有一个现有的 .dll/.so 文件,如 ...
- JAVA一个文件写多个类
JAVA一个文件写多个类,并且是同级类,需注意: 在一个.java文件中可以有多个同级类, 其修饰符只可以public/abstract/final/和无修饰符 public修饰的只能有一个,且必须 ...
- java 从零开始手写 RPC (03) 如何实现客户端调用服务端?
说明 java 从零开始手写 RPC (01) 基于 socket 实现 java 从零开始手写 RPC (02)-netty4 实现客户端和服务端 写完了客户端和服务端,那么如何实现客户端和服务端的 ...
- java 从零开始手写 RPC (04) -序列化
序列化 java 从零开始手写 RPC (01) 基于 socket 实现 java 从零开始手写 RPC (02)-netty4 实现客户端和服务端 java 从零开始手写 RPC (03) 如何实 ...
随机推荐
- javaS的tring和androidS的tring区别是什么?
这是今天阿里电话面试被问到的,在之前确实没有想过(一直以为是一样的),于是面试完之后,我立即打开了源代码,对这两个String类进行了比較,以下是我的发现. 首先我观察了这两个String类所导入的包 ...
- 实用WordPress后台MySQL操作命令
关键字: WordPress MySQL 后台 数据库 地址:http://www.cnblogs.com/txw1958/archive/2013/01/06/wordpress-sql.html ...
- 去除WPF中3D图形的锯齿
原文:去除WPF中3D图形的锯齿 理论上讲PC在计算3D图形的时候是无法避免不出现锯齿的,因为3D图形都是又若干个三角形组成,如果3D图形想平滑就必须建立多个三角形,你可以想象一下正5边形和正100边 ...
- matlab 各种文件的读取(及读写问题的解决)
0. 文本文件 load('**.mat') load('**.mat', '-ascii') load('-mat', filename) load('-ascii', filename) 1. 音 ...
- bigdata_mac下安装spark_scala
Java 下载安装Mac对应版本的JDK. Apache-spark $ brew update $ brew info apache-spark $ brew install apache-spar ...
- springboot 集成oauth2
未实现.首先实现spring security. 1. 关于oauth2 隐隐觉得集成oauth2,用好它是一个不太简单的事儿,需要对oauth2了解一番. oauth2比较好的参考,都是别人原创文章 ...
- boost库交叉编译(Linux生成ARM的库)
1. 环境: Linux系统:Ubuntu 14.04 编译工具:arm-fsl-linux-gnueabi-gcc 2.下载boost源码: 地址:https://sourceforge.net/p ...
- mysql 优化 读写分离 主从复制
1:mysql所在服务器内核 优化 ---------此优化可由系统运维人员完成 2:mysql配置参数优化(my.cnf) -------- 此优化需进行压力测试来进行参数调整 3:sql语句及表 ...
- delphi获取dll的函数列表
找了几个,终于找到一个好用的 function GetDLLFileExports( szFileName: PChar; mStrings: TStrings): Boolean;var hFi ...
- c#Code Contracts代码协定
Code Contracts的命名空间:System.Diagnostics.Contracts 集合1. 安装Code Contracts for .NET插件Contracts.devlab9ts ...