依賴包:
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