当前位置: 首页 > 知识库问答 >
问题:

无法建立与 Exchange Web Service - Java API 的连接

祁博雅
2023-03-14

我正在测试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)

我不明白当前的代码有什么问题。你有任何线索,或至少一些测试来尝试吗?

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

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

<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>

编辑

我又做了一个测试。这一次,我使用默认的凭证——因此我自己的电子邮件帐户——使用< code > service . setusedefaultcredentials(true);而不是设置< code>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服务器端的任何内容。有没有办法使身份验证成功?

共有3个答案

南门承教
2023-03-14

这是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;
    }

}

皇甫夕
2023-03-14

我得到了上面提到的错误,并花了很多时间试图修复它。我的最终解决方案是完全放弃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;
       }
   }
}

您需要获取javamail-1.4.7并将邮件.jar从(http://www.oracle.com/technetwork/java/index-138643.html)加载到项目中。

我们做了一件事来说明这种情况,那就是下载雷鸟邮件客户端,它可以自动发现有关exchange服务器的信息,以确保我们所有的设置都是正确的。

费子濯
2023-03-14

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

 类似资料:
  • 问题内容: 我正在尝试从MS AD中检索一些信息:特定分支机构的成员,部门名称,职位等。 我使用了很多示例,包括Apache Directory LDAP API 和UnboundID,但是我无法与AD建立连接。 RDN: 为了进行搜索,我使用以下过滤器: 当我使用中的数据创建目录上下文时,出现异常: 如果未指定密码,则会出现以下异常: 我已验证我的帐户未锁定。 根据常见的活动目录LDAP绑定错误

  • 我在docker中运行了elasticsearch 8.1,其中包含以下docker compose文件: 我正在尝试使用org.elasticsearch.client.RestClient向es集群发出一个简单的GET请求。 请求: Rest客户端初始化: 主要方法: buildClusterHosts()方法正确地构建了一个HttpHost数组(在本例中只有一个),并将其提供给rest客户端

  • 你好在我的代码它打破了我的请求,我尝试了几次,但1-2小时后bot状态不再改变。 我在ftp服务器上托管这些文件。 以后从未检索到任务异常:异常=ConnectionError(MaxRetryError(“HTTPConnectionPool(host='username.mydomain',port=80”):url超过最大重试次数:/project/total_visit/count.txt

  • 我发现自己在一个工作,我必须与Windows服务器(2012)-我从来没有问题与建立DB连接,但现在我似乎没有找到任何正确的解决方案。 我将向您展示我的连接php代码: 这是我在浏览器中得到的结果: SQLSTATE[HY000][2002]是一家大型计算机公司。 翻译成英文: 无法建立连接,因为目标机器主动拒绝它。 注意:我下载了mssql驱动程序和sqlsrv驱动程序,并将它们解压缩到/ext

  • 在使用PHP 5.6.3在Ubuntu 14.04上克隆存储库后,我无法运行PHP composer。phar selfupdate都不是php composer。phar更新。我收到以下消息: 我认为问题应该出在我本地拥有的证书上,但我无法想象如何解决它。 这是作曲家。json:

  • 我正在尝试将Travis CI集成到我的rails应用程序中。在我的本地机器(ubuntu,windows)上一切工作都很好,但是在travis主机上有一个连接错误。下面是我的配置。 正在创建myapp_postgres_1 无法连接到服务器:连接被拒绝服务器是否在主机“Postgres”(172.18.0.2)上运行并接受端口5432上的TCP/IP连接?无法为{“adapter”=>“post

  • 下面是Qpid客户端的配置,使用Camel上下文连接Artemis Broker。 上下文文件正像预期的那样开始,但是在本例中,qpid客户机无法连接到Apache Artemis 2.14.0代理。 我所看到的只是消费者端的一些线程块。 common-context.xml 注意:在使用CAMEL2.20.0版本时,即使在所有上下文都得到的情况下,这个单个xml文件中也有两个camel上下文

  • 最近我在用JavaEE做这个小项目,我需要使用derby数据库,但每次我去服务- 无法连接。无法建立到jdbc的连接:derby://localhost:1527//sample使用组织。阿帕奇。德比。jdbc。ClientDriver(java.netConnectException:在端口1527上连接到服务器本地主机时出错,消息为Connection拒绝:connect.)。 这个例外: 有