JavaMail 交换认证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1713116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 21:49:07  来源:igfitidea点击:

JavaMail Exchange Authentication

javaauthenticationweb-applicationsexchange-serverjavamail

提问by rafaelochoa

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.

我正在尝试使用 JavaMail 从我的应用程序中使用 Exchange 身份验证来执行此操作。有人可以给我一个指南吗?身份验证后,我需要发送邮件,这是我使用 JavaMail 的主要原因。我发现的所有链接都谈到了这个问题,但我认为这必须是从 Java 中轻松完成的任务。提前致谢。

回答by David Rabinowitz

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.

此代码基于示例代码随java邮件下载而来。

回答by BalusC

After authentication I need to send mails

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

The below example works fine here with Exchange servers:

以下示例适用于 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) {}
}

回答by tenebaul

Exchange does not start SMTPservice by default, so we can't use SMTP protocolto 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.

Exchange默认不启动SMTP服务,所以我们无法使用SMTP protocol连接到 Exchange 服务器并尝试发送电子邮件。BalusC 可以很好地使用上述代码,因为您的邮件服务器管理员在 Exchange 上启用了 SMTP 服务。而在大多数情况下,SMTP 被禁用。我也在寻找解决方案。

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.

是我发现的最佳答案,但令人沮丧的是,您必须在 60 天后付款。

回答by BrunoJCM

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

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

回答by Populus

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

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

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

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

回答by Marco

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:

尝试了 ews-java-api,正如 Populus 在之前的评论中所提到的。它是在带有 jdk1.6 的 Java SE 环境中完成的,它的工作原理非常棒。
这些是我必须与我的样本相关联的库:

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

希望能帮助到你。

回答by Java Basketball

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

首先,您应该导入 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>

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

其次,你应该新建一个名为.MailUtil.java一些Exchange ServersSMTP默认不启动服务的java类,所以我们使用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();

    }
}

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

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