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

posted on 2019-06-12 19:37  SolitaryBoy  阅读(899)  评论(0)    收藏  举报

导航