Java---使用EWS 写个ExchangeMailUtil

Posted itczybk

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

如果地址是别名,如何使用 ews-java-api 识别收件人电子邮件?

ews-java-api:项目更新错误:至少一个收件人无效

如何使用 EWS Java API (Exchange Web Service) 设置联系人标题?

使用 OAuth 令牌验证和获取 EWS 数据

从 Java 应用程序调用 https://outlook.office365.com/EWS/Exchange.asmx 时出现随机 SSLHandshakeException

使用 EWS API 发送电子邮件时控制消息编码