JAVA实现Exchange获取未读邮件列表(点击邮件标题访问到该邮件)

1.依赖jar包

<dependency>
    <groupId>com.microsoft.ews-java-api</groupId>
    <artifactId>ews-java-api</artifactId>
    <version>2.0</version>
</dependency>

2.自定义邮件属性类

import java.util.Date;
public class ExChangeMailModel {
	private String id;
	private String subject;
	private Date dateTimeReceived;
	private Boolean isRead;
	private String body;
}

3.邮件工具类

import java.net.URI;
import java.util.ArrayList;
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.WellKnownFolderName;
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.ItemSchema;
import microsoft.exchange.webservices.data.credential.ExchangeCredentials;
import microsoft.exchange.webservices.data.credential.WebCredentials;
import microsoft.exchange.webservices.data.search.FindItemsResults;
import microsoft.exchange.webservices.data.search.ItemView;
import microsoft.exchange.webservices.data.search.filter.SearchFilter;

public class ExChangeMail {
	private String mailServer;
    private String user;
    private String password;
    private String domain;
    
    public ExChangeMail(String mailServer, String user, String password) {
        this.mailServer = mailServer;
        this.user = user;
        this.password = password;
    }

    public ExChangeMail(String mailServer, String user, String password, String domain) {
        this.mailServer = mailServer;
        this.user = user;
        this.password = password;
        this.domain = domain;
    }
    
    public ArrayList<EmailMessage> receive(int max, SearchFilter searchFilter) throws Exception {
        ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
        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 (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 {
            // e.g. new SearchFilter.SearchFilterCollection(
            // LogicalOperator.Or, new SearchFilter.ContainsSubstring(ItemSchema.Subject, "EWS"),
            // new SearchFilter.ContainsSubstring(ItemSchema.Subject, "API"))
            findResults = service.findItems(inbox.getId(), searchFilter, view);
        }
        service.loadPropertiesForItems(findResults, PropertySet.FirstClassProperties);
        ArrayList<EmailMessage> result = new ArrayList<>();
        for (Item item : findResults.getItems()) {
            EmailMessage message = (EmailMessage) item;
            result.add(message);
        }
        return result;
    }
    
    public ArrayList<EmailMessage> receive(int max) throws Exception {
        return receive(max, null);
    }

    /**
     * 收取邮件
     * @throws Exception
     */
    public ArrayList<EmailMessage> receive() throws Exception {
        return receive(0, null);
    }
}

4.controller.java

import java.net.URI;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.icss.cooperative.common.sso.UserInfoEx;
import com.icss.cooperative.synergy.rone.service.ExChangeMialService;
import com.icss.cooperative.synergy.rone.tool.AdUtil;
import com.icss.cooperative.tool.util.LogUtil;
import microsoft.exchange.webservices.data.core.ExchangeService;
import microsoft.exchange.webservices.data.core.enumeration.misc.ConnectingIdType;
import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import microsoft.exchange.webservices.data.core.enumeration.property.WellKnownFolderName;
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.credential.ExchangeCredentials;
import microsoft.exchange.webservices.data.credential.WebCredentials;
import microsoft.exchange.webservices.data.misc.ImpersonatedUserId;
import microsoft.exchange.webservices.data.search.FindItemsResults;
import microsoft.exchange.webservices.data.search.ItemView;
import microsoft.exchange.webservices.data.search.filter.SearchFilter;

@Controller
public class SystemMailssoController {
	@Resource
	private ExChangeMialService exChangeMialService;
	/**
	 * Exchange单点登录
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/exChange/getMailByUrl",method = RequestMethod.POST)
	@ResponseBody
	public Map<String,String> getMailByUrl(HttpServletRequest request){
		Map<String,String> map = new HashMap<String,String>();
		UserInfoEx userInfoEx = (UserInfoEx)request.getSession().getAttribute(UserInfoEx.USERINFO_EX);
		String userName = userInfoEx.getUserInfo().getEmail1();
		String passWord = AdUtil.getPersonPWD(userInfoEx.getUserInfo().getPersonUuid());
		map.put("userName", userName);
		map.put("passWord", passWord);
		return map;
	}
	
	/**
	 * 获取未读邮件
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/exChange/getMailByList",method = RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> getMailByList(HttpServletRequest request){
		Map<String,Object> map = new HashMap<String,Object>();
		
		//String userName = userInfoEx.getUserInfo().getEmail1();
		//String passWord = AdUtil.getPersonPWD(userInfoEx.getUserInfo().getPersonUuid());
		String serviceUrl = "https://xx.xx.com/EWS/exchange.asmx";
		try {
			UserInfoEx userInfoEx = (UserInfoEx)request.getSession().getAttribute(UserInfoEx.USERINFO_EX);
			map = exChangeMialService.getMailLists(serviceUrl, userInfoEx.getUserInfo().getEmail1(), AdUtil.getPersonPWD(userInfoEx.getUserInfo().getPersonUuid()),9);
		} catch (Exception e) {
			// TODO: handle exception
			LogUtil.errorLog(e);
		}
		
		return map;
	}
	
	@RequestMapping(value="/exChange/openMail",method = RequestMethod.GET)
	@ResponseBody
	public ModelAndView openMail(HttpServletRequest request,String id) throws Exception{
		UserInfoEx userInfoEx = (UserInfoEx)request.getSession().getAttribute(UserInfoEx.USERINFO_EX);
		ModelAndView view = new ModelAndView("/index/owaLogin");
		Map<String,Object> map = new HashMap<String,Object>();
		view.addObject("userName",userInfoEx.getUserInfo().getEmail1());
		view.addObject("passWord",AdUtil.getPersonPWD(userInfoEx.getUserInfo().getPersonUuid()));
		view.addObject("domain","xx.com");
		String destination="https://xx.xx.com/owa/";
		System.out.println(id);
		String[] idarray =  id.split("&");
		for (int i = 0; i < idarray.length; i++) {
			if(idarray[i].startsWith("id=")){
				String idString = idarray[i];
				idarray[i] = "id="+URLEncoder.encode(idString.substring(3),"UTF-8");
			}
		}
		id = StringUtils.join(idarray, "&");
		System.out.println(id);
		destination+=id;
		//String userName = userInfoEx.getUserInfo().getEmail1();
		//String passWord = AdUtil.getPersonPWD(userInfoEx.getUserInfo().getPersonUuid());
		String serviceUrl = "https://xx.xx.com/EWS/exchange.asmx";
		view.addObject("destination",destination);
		try {
			//UserInfoEx userInfoEx = (UserInfoEx)request.getSession().getAttribute(UserInfoEx.USERINFO_EX);
			//map = exChangeMialService.getMailLists(serviceUrl, "", "");
		} catch (Exception e) {
			// TODO: handle exception
			LogUtil.errorLog(e);
		}
		
		return view;
	}
	
	public String getCount(String userName, String passWord, String domain, String uri, String suffix, String sid) throws Exception {
        String count = "0";
       /* ExchangeService service = new ExchangeService(
                ExchangeVersion.Exchange2010_SP1);*/
        ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
        ExchangeCredentials credentials = new WebCredentials(userName, passWord,domain);
        //ExchangeCredentials credentials = new WebCredentials("bbbb", "Aa123456","fr");
        service.setCredentials(credentials);
        ImpersonatedUserId other= new ImpersonatedUserId(ConnectingIdType.SmtpAddress, sid+suffix);
        service.setImpersonatedUserId(other);
        service.setUrl(new URI(uri));
        //service.setTraceEnabled(true);
        // 服务地址
        try {
            Folder inbox = Folder.bind(service, WellKnownFolderName.Inbox);
            // 收件箱
            // System.out.println("未读邮件数:" + inbox.getUnreadCount());

            count = inbox.getUnreadCount() + "";
        } catch (Exception e) {
        //  e.printStackTrace();
        }
        return count;
    }
	
	/*public static void main(String[] args) throws Exception{ 
		ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010); 
		ExchangeCredentials credentials = new WebCredentials("", ""); 
		//service.setCredentials(credentials); service.setUrl(new URI("https://xxxx/a/b?wsdl"));//服务地址 
		service.setCredentials(credentials); service.setUrl(new URI("https://xx.xx.com/EWS/exchange.asmx"));
		Folder inbox = Folder.bind(service, WellKnownFolderName.Inbox);//收件箱 
		System.out.println("未读邮件数:" + inbox.getUnreadCount()); 
		ItemView view = new ItemView(10); 
		view.setOffset(view.getOffset()); 
		FindItemsResults<Item> findResults = service .findItems(inbox.getId(),new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false), view); 
		for (Item item : findResults .getItems()) { 
			EmailMessage message = EmailMessage.bind(service, item.getId()); 
			System.out.print(message.getSender().toString() + ": " + item.getSubject()); } 
		System.out.println("------------------------");
	} */

}

5.实现类

import java.net.URI;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Service;
import com.icss.cooperative.synergy.rone.model.ExChangeMail;
import com.icss.cooperative.synergy.rone.model.ExChangeMailModel;
import com.icss.cooperative.synergy.rone.service.ExChangeMialService;
import com.icss.cooperative.tool.util.LogUtil;
import microsoft.exchange.webservices.data.core.ExchangeService;
import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import microsoft.exchange.webservices.data.core.enumeration.property.WellKnownFolderName;
import microsoft.exchange.webservices.data.core.enumeration.service.ConflictResolutionMode;
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.schema.EmailMessageSchema;
import microsoft.exchange.webservices.data.credential.ExchangeCredentials;
import microsoft.exchange.webservices.data.credential.WebCredentials;
import microsoft.exchange.webservices.data.search.filter.SearchFilter;

@Service
public class ExChangeMialServiceImpl implements ExChangeMialService{
	@Override
    public Map<String,Object> getMailLists(String serviceUrl, String userName, String passWord, int num){
    	Map<String,Object> map = new HashMap<String,Object>();
    	ExChangeMail mailUtil = new ExChangeMail(serviceUrl, userName, passWord);
		//ExchangeMailUtil mailUtil = new ExchangeMailUtil();
		/*mailUtil.setMailServer("https://mail.kmgdgs.com/EWS/exchange.asmx");
		mailUtil.setUser("");
		mailUtil.setPassword("");*/
		ArrayList<EmailMessage> mails;		
		try {
			SearchFilter searchFilter = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead,false);
			mails = mailUtil.receive(num,searchFilter);
			//map.put("mails", mails);
			List<ExChangeMailModel> list = new ArrayList<>();
			for (EmailMessage mail : mails) {
				ExChangeMailModel exMailModel = new ExChangeMailModel();
	            //System.out.println("邮件标题: " + mail.getSubject());
	            //System.out.println("接收时间: " + mail.getDateTimeReceived());
	            //System.out.println("发送人: " + mail.getFrom().getName() + ", 地址: " + mail.getFrom().getAddress());
	            //System.out.println("已读:" + mail.getIsRead());
	            exMailModel.setSubject(mail.getSubject());
	            exMailModel.setBody(mail.getBody().toString());
	            exMailModel.setIsRead(mail.getIsRead());
	            exMailModel.setDateTimeReceived(mail.getDateTimeReceived());
	            exMailModel.setId(mail.getWebClientReadFormQueryString());
	            //System.out.println("id:" + mail.getWebClientReadFormQueryString());
	            //System.out.println("id:" + mail.getWebClientReadFormQueryString().substring(30));
	            list.add(exMailModel);
	            // 更新已读
	            /*if (mail.getIsRead()) {
	                mail.setIsRead(false);
	                mail.update(ConflictResolutionMode.AlwaysOverwrite);
	            }*/
	            //EMTextMessageBody txtBody = (EMTextMessageBody) message.getBody();
	            //txtBody.getMessage()
	            //System.out.println("邮件内容 :" + mail.getBody());
	            // 处理附件
	            /*List<Attachment> attachs = mail.getAttachments().getItems();
	            try {
	                if (mail.getHasAttachments()) {
	                    for (Attachment attach : attachs) {
	                        if (attach instanceof FileAttachment) {
	                            //接收邮件到临时目录
	                            //System.out.println("主题"+attach.getName());
	                            //File tempZip = new File("/tmp", attach.getName());
	                            //((FileAttachment) attach).load(tempZip.getPath());
	                        }
	                    }
	                    //删除邮件
	                    //mail.delete(DeleteMode.HardDelete);
	                }
	            } catch (Exception e) {
	                e.printStackTrace();
	            }*/	            
	        }
			map.put("mails", list);			
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			LogUtil.errorLog(e1);
		}
		return map;
	}

	public int mailNum(String userName, String passWord){ 
		ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010); 
		ExchangeCredentials credentials = new WebCredentials("hukun", "422000"); 
		//service.setCredentials(credentials); service.setUrl(new URI("https://xxxx/a/b?wsdl"));//服务地址 
		int num=50;
		Folder inbox;
		try {
			service.setCredentials(credentials); service.setUrl(new URI("https://xx.xx.com/EWS/exchange.asmx"));
			inbox = Folder.bind(service, WellKnownFolderName.Inbox);
			System.out.println("未读邮件数:" + inbox.getUnreadCount()); 
			num = inbox.getUnreadCount();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			LogUtil.errorLog(e);
		}//收件箱 
		return num;
		/*ItemView view = new ItemView(10); 
		view.setOffset(view.getOffset()); 
		FindItemsResults<Item> findResults = service .findItems(inbox.getId(),new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false), view); 
		for (Item item : findResults .getItems()) { 
			EmailMessage message = EmailMessage.bind(service, item.getId()); 
			System.out.print(message.getSender().toString() + ": " + item.getSubject()); } */	
	} 
}

6.前端js

$.each(programme_data, function(i, todoIssue){
			var nowDate = new Date();
			var datenew = format(nowDate);
			if(todoIssue.isRead){return;}
			if(i >= 9){return;}
			var id = todoIssue.id;
			var issueName = "";
			var issueNamequan = todoIssue.subject.replace(/ /g,'&#32;');
			
			
			issueName = todoIssue.subject;//getInterceptedStr(todoIssue.subject,30);
			//alert(issueName);
			
			/*if(todoIssue.subject.length<=16){
				issueName = todoIssue.subject;
			}else{
				issueName = todoIssue.subject.substring(0, 16)+"...";
			}*/
					//日志主题
			fromDate=dataFormatStr(new Date(todoIssue.dateTimeReceived),"yyyy-MM-dd").substring(5,10);
			//alert(fromDate);
			//var fromDate = todoIssue.dateTimeReceived;			//接收日期
				//fromDate=fromDate.substring(11,16);
			var doIssueText = "";
			
			if(controlName == 'programmeList1'){ 
				doIssueText = '<div class="pw_rtow_data_box_list">'+
								'<div class="pw_rtow_data_box_list_title"><p>'+ fromDate +'</p></div>'+
								'<div class="pw_rtow_data_box_list_data"><a title='+issueNamequan+' href=javascript:openMail("'+todoIssue.id+'") >'+ issueName +'</a></div>'+
							'</div>';
			}
			num++;
			toDoListUl.append(doIssueText);
		});

function openMail(id){
	window.open('/xx/exChange/openMail?id='+encodeURIComponent(id));
}

7.owaLogin.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%
String destination = (String)request.getAttribute("destination");
String username = (String)request.getParameter("username");
String password = (String)request.getParameter("password");
%>

<html>
  <head>
    <title>OWA登陆</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	
	<script type="text/javascript">
	function bodyOnload(){
        //var username = "<%=username%>";
        //var password = "<%=password%>";
        //alert("username===>" + username);
        //alert("password===>" + password);
		
		document.cookie = "PBack=0; domain=xx.com;path=/";
		//document.logonForm.destination.value=document.logonForm.destination.value.replace("&amp;","&").replace("@","%40");
		var destext = document.logonForm.destination.value;
        //alert("destext===>" + destext);
		var newtext = destext.replace("&amp;","&").replace("@","%40");
		//alert("newtext===>" + newtext);
		document.logonForm.submit();
	}
	</script>
  </head>
  
<body onload="bodyOnload()">
<form name="logonForm" action="https://xx.xx.com/owa/auth/owaauth.dll" method="post">
<input type="hidden" name="destination" id="destination" value="<%=destination%>"/>
<input type="hidden" name="flags" value="0"/>
<input type="hidden" name="forcedownlevel" value="0"/>
<input type="hidden" name="trusted" value="0"/>
<input type="hidden" name="isUtf8"  value="1"/>
<input type="hidden" name="username" id="username" value="${userName }"/>
<input type="hidden" name="password" id="password" value="${passWord }"/>
</form>
</body>
</html>

©️2020 CSDN 皮肤主题: 1024 设计师:上身试试 返回首页