1. 程式人生 > >使用Exchange讀取郵件、傳送郵件

使用Exchange讀取郵件、傳送郵件

問題

由於公司郵箱並未開放POP3收信埠,但配置exchange後,手機郵件客戶端可以收發郵件,因此決定使用exchange協議收發郵件。但測試過程中發現登入時反覆提示“440 Login Timeout ”錯誤,使用者名稱密碼並沒有出錯。

解決方案

OWA(Outlook Web Access)提供的EWS(Exchange Web Service)的協議地址原來是https://Exchange郵件伺服器名/EWS/Exchange.asmx,修改後即可登入了。

程式碼

官方文件地址
專案中新增ews-java-api.jar後即可,maven專案中新增

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

工具類程式碼如下:


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.SortDirection; 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.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.property.complex.Attachment; import microsoft.exchange.webservices.data.property.complex.FileAttachment; 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; import java.io.File; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; /** * Exchange郵件服務工具類 * * @author Yang Cheng * @date 2017-02-13 */ public class ExchangeMailUtil { private String mailServer; private String user; private String password; private String domain; public ExchangeMailUtil(String mailServer, String user, String password) { this.mailServer = mailServer; this.user = user; this.password = password; } public ExchangeMailUtil(String mailServer, String user, String password, String domain) { this.mailServer = mailServer; this.user = user; this.password = password; this.domain = domain; } public static void main(String[] args) throws Exception { // Outlook Web Access路徑通常為/EWS/exchange.asmx ExchangeMailUtil mailUtil = new ExchangeMailUtil("https://mail.domain.com/EWS/exchange.asmx", "[email protected]", "xx"); // 接收郵件 ArrayList<EmailMessage> mails = mailUtil.receive(10); for (EmailMessage mail : mails) { System.out.println("郵件標題: " + mail.getSubject()); System.out.println("接收時間: " + mail.getDateTimeReceived()); System.out.println("傳送人: " + mail.getFrom().getName() + ", 地址: " + mail.getFrom().getAddress()); System.out.println("已讀:" + mail.getIsRead()); // 更新已讀 if (!mail.getIsRead()) { mail.setIsRead(true); mail.update(ConflictResolutionMode.AlwaysOverwrite); } //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(); } System.out.println(); } // 傳送郵件 //mailUtil.send("Subject", new String[] { "[email protected]" }, null, "content"); } /** * 建立郵件服務 * * @return 郵件服務 */ private 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 { ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); 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; } /** * 收取所有郵件 * * @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); } }