2

我想用 Java 和 Microsoft 交换服务器 API 发送电子邮件。我按照文档中的说明进行操作,但总是遇到异常。

所有参数(用户名、密码、域和 uri 都正确)。我已经使用 Microsoft 的 EWS 编辑器测试了此参数,并且使用该编辑器我得到了连接。

我的代码是这样的:

import microsoft.exchange.webservices.data.EmailMessage;
import microsoft.exchange.webservices.data.ExchangeCredentials;
import microsoft.exchange.webservices.data.ExchangeService;
import microsoft.exchange.webservices.data.ExchangeVersion;
import microsoft.exchange.webservices.data.MessageBody;
import microsoft.exchange.webservices.data.WebCredentials;

public class Mail {

ExchangeService service = new ExchangeService(
        ExchangeVersion.Exchange2010_SP2);

ExchangeCredentials credentials = new WebCredentials("user",
        "passwort", "domain");

public void sendMail() throws Exception {

    service.setTraceEnabled(true);
    java.net.URI uri = new java.net.URI(
            "https://********/ews/exchange.asmx");

    service.setCredentials(credentials);
    service.setUrl(uri);

    System.out.println(service.getServerInfo());

    EmailMessage msg = new EmailMessage(service);
    msg.setBody(MessageBody
            .getMessageBodyFromText("Sent using the EWS Managed API."));
    msg.getToRecipients().add("send mail to ");
    msg.send();
}

public static void main(String[] args) throws Exception {
    Mail mail = new Mail();
    mail.sendMail();
}

例外是:

Exception in thread "main" microsoft.exchange.webservices.data.EWSHttpException: Connection not established
at microsoft.exchange.webservices.data.HttpClientWebRequest.throwIfConnIsNull(HttpClientWebRequest.java:394)
at microsoft.exchange.webservices.data.HttpClientWebRequest.getResponseCode(HttpClientWebRequest.java:370)
at microsoft.exchange.webservices.data.EwsUtilities.formatHttpResponseHeaders(EwsUtilities.java:597)
at microsoft.exchange.webservices.data.ExchangeServiceBase.traceHttpResponseHeaders(ExchangeServiceBase.java:467)
at microsoft.exchange.webservices.data.ExchangeServiceBase.processHttpResponseHeaders(ExchangeServiceBase.java:1043)
at microsoft.exchange.webservices.data.SimpleServiceRequestBase.internalExecute(SimpleServiceRequestBase.java:58)
at microsoft.exchange.webservices.data.MultiResponseServiceRequest.execute(MultiResponseServiceRequest.java:144)
at microsoft.exchange.webservices.data.ExchangeService.internalCreateItems(ExchangeService.java:464)
at microsoft.exchange.webservices.data.ExchangeService.createItem(ExchangeService.java:535)
at microsoft.exchange.webservices.data.Item.internalCreate(Item.java:215)
at microsoft.exchange.webservices.data.EmailMessage.internalSend(EmailMessage.java:125)
at microsoft.exchange.webservices.data.EmailMessage.send(EmailMessage.java:253)
at de.ruv.SendMail.Mail.sendMail(Mail.java:40)
at de.ruv.SendMail.Mail.main(Mail.java:45)
4

1 回答 1

0

改变

ExchangeCredentials credentials = new WebCredentials("user", "password", "domain");

service.Credentials = new NetworkCredential("user", "password", "domain");
于 2015-03-19T13:44:05.723 回答