JavaMail 交换身份验证

发布于 2024-08-10 18:56:05 字数 155 浏览 3 评论 0原文

我正在尝试使用 JavaMail 从我的应用程序中使用 Exchange 身份验证来执行此操作。有人可以给我指导吗? 身份验证后,我需要发送邮件,这是我使用 JavaMail 的主要原因。 我发现的所有链接都讨论了与此相关的问题,但我认为这对于 Java 来说一定是一项简单的任务。 提前致谢。

I'm trying to use Exchange authentication from my app using JavaMail to do this. Could some one give me a guide to do this?
After authentication I need to send mails that's the main reason that I'm using JavaMail.
All the links that I found talks about problems with this but I think this must be an easy task to do from Java.
Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

清晨说晚安 2024-08-17 18:56:05

这是一个好问题!我已经解决了这个问题。

首先,您应该导入 jar ews-java-api-2.0.jar。如果你使用maven,你可以将以下代码添加到你的pom.xml

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

其次,你应该新建一个名为MailUtil.java的java类。一些Exchange服务器不会启动<默认情况下为 code>SMTP 服务,因此我们使用 Microsoft Exchange WebServices(EWS) 而不是 SMTP 服务。

MailUtil.java

package com.spacex.util;


import microsoft.exchange.webservices.data.core.ExchangeService;
import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import microsoft.exchange.webservices.data.core.service.item.EmailMessage;
import microsoft.exchange.webservices.data.credential.ExchangeCredentials;
import microsoft.exchange.webservices.data.credential.WebCredentials;
import microsoft.exchange.webservices.data.property.complex.MessageBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;

/**
 * Exchange send email util
 *
 * @author vino.dang
 * @create 2017/01/08
 */
public class MailUtil {

    private static Logger logger = LoggerFactory.getLogger(MailUtil.class);



    /**
     * send emial
     * @return
     */
    public static boolean sendEmail() {

        Boolean flag = false;
        try {
            ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1); // your server version
            ExchangeCredentials credentials = new WebCredentials("vino", "abcd123", "spacex"); // change them to your email username, password, email domain
            service.setCredentials(credentials);
            service.setUrl(new URI("https://outlook.spacex.com/EWS/Exchange.asmx")); //outlook.spacex.com change it to your email server address
            EmailMessage msg = new EmailMessage(service);
            msg.setSubject("This is a test!!!"); //email subject
            msg.setBody(MessageBody.getMessageBodyFromText("This is a test!!! pls ignore it!")); //email body
            msg.getToRecipients().add("[email protected]"); //email receiver
//        msg.getCcRecipients().add("[email protected]"); // email cc recipients
//        msg.getAttachments().addFileAttachment("D:\\Downloads\\EWSJavaAPI_1.2\\EWSJavaAPI_1.2\\Getting started with EWS Java API.RTF"); // email attachment
            msg.send(); //send email
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return flag;

    }


    public static void main(String[] args) {

        sendEmail();

    }
}

如果您想了解更多详细信息,请参阅 https ://github.com/OfficeDev/ews-java-api/wiki/Getting-Started-Guide

It is a good question! I have solved this issue.

First, you should import the jar ews-java-api-2.0.jar. if you use maven, you would add the following code into your pom.xml

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

Secondly, you should new java class named MailUtil.java.Some Exchange Servers don't start SMTP service by default, so we use Microsoft Exchange WebServices(EWS) instead of SMTP service.

MailUtil.java

package com.spacex.util;


import microsoft.exchange.webservices.data.core.ExchangeService;
import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import microsoft.exchange.webservices.data.core.service.item.EmailMessage;
import microsoft.exchange.webservices.data.credential.ExchangeCredentials;
import microsoft.exchange.webservices.data.credential.WebCredentials;
import microsoft.exchange.webservices.data.property.complex.MessageBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;

/**
 * Exchange send email util
 *
 * @author vino.dang
 * @create 2017/01/08
 */
public class MailUtil {

    private static Logger logger = LoggerFactory.getLogger(MailUtil.class);



    /**
     * send emial
     * @return
     */
    public static boolean sendEmail() {

        Boolean flag = false;
        try {
            ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1); // your server version
            ExchangeCredentials credentials = new WebCredentials("vino", "abcd123", "spacex"); // change them to your email username, password, email domain
            service.setCredentials(credentials);
            service.setUrl(new URI("https://outlook.spacex.com/EWS/Exchange.asmx")); //outlook.spacex.com change it to your email server address
            EmailMessage msg = new EmailMessage(service);
            msg.setSubject("This is a test!!!"); //email subject
            msg.setBody(MessageBody.getMessageBodyFromText("This is a test!!! pls ignore it!")); //email body
            msg.getToRecipients().add("[email protected]"); //email receiver
//        msg.getCcRecipients().add("[email protected]"); // email cc recipients
//        msg.getAttachments().addFileAttachment("D:\\Downloads\\EWSJavaAPI_1.2\\EWSJavaAPI_1.2\\Getting started with EWS Java API.RTF"); // email attachment
            msg.send(); //send email
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return flag;

    }


    public static void main(String[] args) {

        sendEmail();

    }
}

if you want to get more detail, pls refer to https://github.com/OfficeDev/ews-java-api/wiki/Getting-Started-Guide

阿楠 2024-08-17 18:56:05

身份验证后我需要发送邮件

下面的示例在 Exchange 服务器上运行良好:

Properties properties = new Properties();
properties.put("mail.transport.protocol", "smtp");
properties.put("mail.smtp.host", "mail.example.com");
properties.put("mail.smtp.port", "2525");
properties.put("mail.smtp.auth", "true");

final String username = "username";
final String password = "password";
Authenticator authenticator = new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password);
    }
};

Transport transport = null;

try {
    Session session = Session.getDefaultInstance(properties, authenticator);
    MimeMessage mimeMessage = createMimeMessage(session, mimeMessageData);
    transport = session.getTransport();
    transport.connect(username, password);
    transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
} finally {
    if (transport != null) try { transport.close(); } catch (MessagingException logOrIgnore) {}
}

After authentication I need to send mails

The below example works fine here with Exchange servers:

Properties properties = new Properties();
properties.put("mail.transport.protocol", "smtp");
properties.put("mail.smtp.host", "mail.example.com");
properties.put("mail.smtp.port", "2525");
properties.put("mail.smtp.auth", "true");

final String username = "username";
final String password = "password";
Authenticator authenticator = new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password);
    }
};

Transport transport = null;

try {
    Session session = Session.getDefaultInstance(properties, authenticator);
    MimeMessage mimeMessage = createMimeMessage(session, mimeMessageData);
    transport = session.getTransport();
    transport.connect(username, password);
    transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
} finally {
    if (transport != null) try { transport.close(); } catch (MessagingException logOrIgnore) {}
}
手长情犹 2024-08-17 18:56:05

对我有用:

Properties props = System.getProperties();
// Session configuration is done using properties. In this case, the IMAP port. All the rest are using defaults
props.setProperty("mail.imap.port", "993");
// creating the session to the mail server
Session session = Session.getInstance(props, null);
// Store is JavaMails name for the entity holding the mails
Store store = session.getStore("imaps");
// accessing the mail server using the domain user and password
store.connect(host, user, password);
// retrieving the inbox folder
Folder inbox = store.getFolder("INBOX");

此代码基于随 java 邮件下载而提供的示例代码。

Works for me:

Properties props = System.getProperties();
// Session configuration is done using properties. In this case, the IMAP port. All the rest are using defaults
props.setProperty("mail.imap.port", "993");
// creating the session to the mail server
Session session = Session.getInstance(props, null);
// Store is JavaMails name for the entity holding the mails
Store store = session.getStore("imaps");
// accessing the mail server using the domain user and password
store.connect(host, user, password);
// retrieving the inbox folder
Folder inbox = store.getFolder("INBOX");

This code is based on the sample code arrives with the download of java mail.

空心空情空意 2024-08-17 18:56:05

Microsoft 发布了用于连接 Exchange Web Service 的开源 API

https://github.com/OfficeDev/ews -java-api

Microsoft released an open sourced API for connecting to Exchange Web Service

https://github.com/OfficeDev/ews-java-api

唔猫 2024-08-17 18:56:05

Exchange默认情况下不会启动SMTP服务,因此我们无法使用SMTP协议连接到Exchange服务器并尝试发送电子邮件。 BalusC 可以与上面的代码一起正常工作,因为您的邮件服务器管理员在 Exchange 上启用了 SMTP 服务。而在大多数情况下 SMTP 被禁用。我也在寻找解决方案。

这是我发现的最好的答案,但多么令人沮丧就是你必须在60天后付款。

Exchange does not start SMTP service by default, so we can't use SMTP protocol to connect to Exchange server and try to send email. BalusC can work fine with the above code because your mailserver administrator enabled SMTP service on Exchange.while in most cases SMTP is disabled.I am also looking for solution.

This is the best answer among what i have found, but what a frustration is that you have to pay for it after 60 days.

笑咖 2024-08-17 18:56:05

某些 Exchange 服务器未启用 smtp 协议。
在这些情况下,您可以使用 DavMail

Some Exchange servers don't have smtp protocol enabled.
In these cases you can use DavMail.

捂风挽笑 2024-08-17 18:56:05

尝试了 ews-java-api,正如 Populus 在之前的评论中提到的那样。它是在 Java SE 环境下使用 jdk1.6 完成的,并且效果非常好。
这些是我必须与我的示例关联的库:

  • commons-cli-1.2.jar
  • commons-codec-1.10.jar
  • commons-lang3-3.1.jar
  • commons-logging-1.2.jar
  • ews-java-api-2.0.jar
  • httpclient-4.4.1.jar
  • httpcore-4.4.5.jar

希望有帮助。

Tried the ews-java-api, as mentioned by Populus on a previous comment. It was done on a Java SE environment with jdk1.6 and it works like a charm.
These are the libs that I had to associate with my sample:

  • commons-cli-1.2.jar
  • commons-codec-1.10.jar
  • commons-lang3-3.1.jar
  • commons-logging-1.2.jar
  • ews-java-api-2.0.jar
  • httpclient-4.4.1.jar
  • httpcore-4.4.5.jar

Hope it helps.

水染的天色ゝ 2024-08-17 18:56:05

上面建议的软件包基本上已经报废了。

https://github.com/OfficeDev/ews-java-api

7 月开始2018 年 19 日,Exchange Web Services (EWS) 将不再接收功能更新。虽然该服务将继续接收安全更新和某些非安全更新,但产品设计和功能将保持不变。此更改也适用于 Java 和 .NET 的 EWS SDK。更多信息请参见:https://developer.microsoft.com/en-us/graph/blogs/upcoming-changes-to-exchange-web-services-ews-api-for-office-365/

The package suggested above is essentially at end of life.

From https://github.com/OfficeDev/ews-java-api

Starting July 19th 2018, Exchange Web Services (EWS) will no longer receive feature updates. While the service will continue to receive security updates and certain non-security updates, product design and features will remain unchanged. This change also applies to the EWS SDKs for Java and .NET. More information here: https://developer.microsoft.com/en-us/graph/blogs/upcoming-changes-to-exchange-web-services-ews-api-for-office-365/

囍笑 2024-08-17 18:56:05

已解决

只需将以下内容添加到您的 pom.xml 依赖项中,

    <dependency>
        <groupId>javax.xml.ws</groupId>
        <artifactId>jaxws-api</artifactId>
        <version>2.3.1</version>
    </dependency>

似乎 JAVA 11+ 中缺少 jaxws-api

SOLVED

Just add the follow to your pom.xml dependencies

    <dependency>
        <groupId>javax.xml.ws</groupId>
        <artifactId>jaxws-api</artifactId>
        <version>2.3.1</version>
    </dependency>

seems that jaxws-api is missing in JAVA 11+

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文