5

我正在测试Microsoft Exchange Web Service Java API(1.2 版)以从服务器读取邮件。这是我的代码:

String url = "https://my-server/EWS/exchange.asmx";
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
service.setTraceEnabled(true);
service.setCredentials(new WebCredentials("user", "password"));
service.setUrl(url.toURI());

Mailbox mailbox = new Mailbox("foo@bar.com");
FolderId folder = new FolderId(WellKnownFolderName.Inbox, mailbox);
ItemView view = new ItemView(10);
view.getOrderBy().add(ItemSchema.DateTimeReceived, SortDirection.Descending);
FindItemsResults<Item> items = service.findItems(folder, view);

不幸的是,此代码引发以下错误:

Exception in thread "main" microsoft.exchange.webservices.data.EWSHttpException: Connection not established
    at microsoft.exchange.webservices.data.HttpClientWebRequest.throwIfConnIsNull(Unknown Source)
    at microsoft.exchange.webservices.data.HttpClientWebRequest.getResponseCode(Unknown Source)
    at microsoft.exchange.webservices.data.EwsUtilities.formatHttpResponseHeaders(Unknown Source)
    at microsoft.exchange.webservices.data.ExchangeServiceBase.traceHttpResponseHeaders(Unknown Source)
    at microsoft.exchange.webservices.data.ExchangeServiceBase.processHttpResponseHeaders(Unknown Source)
    at microsoft.exchange.webservices.data.SimpleServiceRequestBase.internalExecute(Unknown Source)
    at microsoft.exchange.webservices.data.MultiResponseServiceRequest.execute(Unknown Source)
    at microsoft.exchange.webservices.data.ExchangeService.findItems(Unknown Source)
    at microsoft.exchange.webservices.data.ExchangeService.findItems(Unknown Source)
    at foo.bar.TestMail.main(TestMail.java:52)

我无法理解当前代码有什么问题。你有什么线索,或者至少有一些测试可以尝试吗?

请注意,https//my-server/exchange.asmx我的 Java 代码可以访问 Web 服务 ( )。

不确定它是否有帮助,但我在日志显示的跟踪中发现:

<Trace Tag="EwsResponse" Tid="1" Time="2013-01-28 10:47:03Z">
<html><head><title>Error</title></head><body>The function requested is not supported
</body></html>
</Trace>

编辑

我又做了一个测试。这一次,我使用默认凭据 - 所以我自己的电子邮件帐户 - 使用service.setUseDefaultCredentials(true);而不是设置WebCredentials对象。连接仍未建立,但我收到另一个错误(我只记录了跟踪日志中有趣的部分):

<h1>You are not authorized to view this page</h1>
You do not have permission to view this directory or page using the credentials that you supplied because your Web browser is sending a WWW-Authenticate header field that the Web server is not configured to accept.
(...)
<h2>HTTP Error 401.2 - Unauthorized: Access is denied due to server configuration.<br>Internet Information Services (IIS)</h2>

当然,我无法访问或更改 Exchange 服务器端的任何内容。有没有办法使认证成功?

4

3 回答 3

1

问题是由于使用的身份验证方案造成的。默认情况下,EWS 使用 NTLM,但我的 Exchange 服务器未配置为接受这种身份验证。我必须使用 LDAP 身份验证。

于 2013-02-05T08:00:34.267 回答
0

我收到了上述错误并花了很多时间试图修复它。我的最终解决方案是完全放弃 EWS 1.2 版并使用以下 javax.mail 代码,如下所示:

package javaapplication4;
import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;


public class JavaApplication4 {
    public static void main(String[] args) throws Exception {
           new JavaApplication4().send_email();
    }
    private void send_email() throws Exception
    {
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.yourserver.net");
        props.put("mail.from", "yourusername@youremailaddress.com");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.ssl.enable", "false");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "587");

        Authenticator authenticator = new Authenticator();
        props.setProperty("mail.smtp.submitter", authenticator.getPasswordAuthentication().getUserName());

        Session session = Session.getInstance(props, authenticator);
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom();
        msg.setRecipients(Message.RecipientType.TO, "yourusername@youremailaddress.com");  
            // also tried @gmail.com
        msg.setSubject("JavaMail ssl test");
        msg.setSentDate(new Date());
        msg.setText("Hello, world!\n");

        Transport transport;
        transport = session.getTransport("smtp");
        transport.connect();
        msg.saveChanges(); 
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();
    }
    private class Authenticator extends javax.mail.Authenticator {
       private PasswordAuthentication authentication;
       public Authenticator() {
           String username = "yourusername@youremailaddress.com";
           String password = "yourpassword";
           authentication = new PasswordAuthentication(username, password);
       }
       protected PasswordAuthentication getPasswordAuthentication() {
           return authentication;
       }
   }
}

您将需要获取并将from ( http://www.oracle.com/technetwork/java/index-138643.htmljavamail-1.4.7 )加载到项目中。 mail.jar

我们做的一件事可以说明情况是下载 Thunderbird 邮件客户端,它可以自动发现有关交换服务器的信息,以确保我们所有的设置都是正确的。

于 2013-08-04T13:52:01.307 回答
0

这是 EWS JAVA api 1.2 的示例,这是您可以尝试的方法之一

package com.ea.connector.exchange;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import microsoft.exchange.webservices.data.BasePropertySet;
import microsoft.exchange.webservices.data.ExchangeCredentials;
import microsoft.exchange.webservices.data.ExchangeService;
import microsoft.exchange.webservices.data.FindItemsResults;
import microsoft.exchange.webservices.data.Item;
 import microsoft.exchange.webservices.data.ItemSchema;
import microsoft.exchange.webservices.data.ItemView;
import microsoft.exchange.webservices.data.LogicalOperator;
import microsoft.exchange.webservices.data.OffsetBasePoint;
import microsoft.exchange.webservices.data.PropertySet;
import microsoft.exchange.webservices.data.SearchFilter;
import microsoft.exchange.webservices.data.SortDirection;
import microsoft.exchange.webservices.data.WebCredentials;
import microsoft.exchange.webservices.data.WebProxy;
import microsoft.exchange.webservices.data.WellKnownFolderName;

import org.apache.commons.httpclient.NTCredentials;

import com.ea.connector.exchange.bean.ExchangeConnectionParamBean;
import com.ea.connector.exchange.util.ExchMessageProperties;
import com.ea.connector.net.ExchGetItemRequest;

public class Test {

protected static ArrayList<String> propertiesToFetch = new ArrayList<String>();

private static ExchangeService mService;

 // private Settings mSettings;
//  
//  private int imailCount;

private Date dStartDate;
private Date dEndDate;
private static ExchangeConnectionParamBean objParamBean;
public void setPropertiesToBeFetched(List<String> filter) {
    propertiesToFetch.addAll(filter);
}
public Date getConnectorStartDate() {
    return dStartDate;
}

public void setConnectorStartDate(Date dStartDate) {
    this.dStartDate = dStartDate;
}

public ExchangeConnectionParamBean getParamBean() {
    return objParamBean;
}

public void setParambean(ExchangeConnectionParamBean objParambean) {
    Test.objParamBean = objParambean;
}

public Date getConnectorEndDate() {
    return dEndDate;
}

public void setConnectorEndDate(Date dEndDate) {
    this.dEndDate = dEndDate;
}


    public static void main(String []args) throws URISyntaxException,Exception
    {
        setCredentialsAndGetExchRequest();
        System.out.println("conncection established");
    }

    protected static ExchGetItemRequest setCredentialsAndGetExchRequest() throws   URISyntaxException,Exception{

        @SuppressWarnings("unused")
        FindItemsResults<Item> resultMails;

        mService = new ExchangeService();
        mService.setUrl(new URI("https://outlook.office365.com/EWS/Exchange.asmx"));
        WebProxy paramWebProxy=new WebProxy("ptbproxy.domain.com",8080);
        mService.setWebProxy(paramWebProxy);

        ExchangeCredentials cred = new WebCredentials("EA_Test_mailbox@domain.com","Zuxu0000");
        NTCredentials ntCredentials = new NTCredentials("EA_Test_mailbox@domain.com","Zuxu0000",                 "",
                "");
        mService.setCredentials(cred);
//          ProxyHost httpProxy=new ProxyHost("ptbproxy.domain.com",8080);
//          UsernamePasswordCredentials cred1=new     UsernamePasswordCredentials("EA_Test_mailbox@domain.com","Zuxu0000");

//          ExchGetItemRequest req = new ExchGetItemRequest(String.valueOf(new URI("http://outlook.office365.com/EWS/Exhanges.asmx")),ntCredentials);
        ExchGetItemRequest req = new ExchGetItemRequest("https://outlook.office365.com/EWS/Exhange.asmx",ntCredentials);

        SearchFilter filter = getSearchFilter();

        PropertySet propertySet = new PropertySet(BasePropertySet.IdOnly);
        ItemView itemView = new ItemView(1000, 0, OffsetBasePoint.Beginning);
        itemView.getOrderBy().add(ItemSchema.DateTimeReceived, SortDirection.Descending);
        itemView.setPropertySet(propertySet);

        //mService.setTimeout(500000);

        req.setProperties(new    ExchMessageProperties().getExchMessageProperties(propertiesToFetch));

              /*Fetching of  mail ids start here*/
                resultMails = getMails(filter, itemView);

                return req;
    }   

    protected static SearchFilter getSearchFilter() throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
    Date d1 = sdf.parse("2014-11-04 00:00:00");
    Date d2 = sdf.parse("2014-11-05 00:00:00");


        SearchFilter greaterThanEq = new SearchFilter.IsGreaterThanOrEqualTo(
                ItemSchema.DateTimeReceived,sdf.format(d1));
        SearchFilter lessThan = new SearchFilter.IsLessThan(
                ItemSchema.DateTimeReceived, sdf.format(d2));
        SearchFilter mailFilter = new SearchFilter.IsEqualTo(
                ItemSchema.ItemClass, "IPM.Note");
      return new SearchFilter.SearchFilterCollection(LogicalOperator.And,
                greaterThanEq, lessThan, mailFilter);
    }
    private static FindItemsResults<Item> getMails(SearchFilter searchFilter,
            ItemView itemView) throws Exception {
        FindItemsResults<Item> items = null;

        int count = 0;

        int maxTries = 3;

        while (true) {
            try {
                items = mService.findItems(WellKnownFolderName.Inbox,
                        searchFilter, itemView);
                break;
            } catch (Exception e) {
                if (++count == maxTries)
                    throw e;
            }
        }

        return items;
    }

}

于 2014-11-20T06:33:34.570 回答