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.
9 Answers
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("123@hotmail.com"); //email receiver
// msg.getCcRecipients().add("test2@test.com"); // 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

- 2,320
- 3
- 24
- 47
-
`535 5.7.3 Authentication unsuccessful` when this error pops up just check if you are using Microsoft exchange user or normal user. – Amila kumara Mar 15 '17 at 12:23
-
@amilarajans you should replace the url, user, password to yourself – Python Basketball Mar 17 '17 at 02:06
-
@Dang Thank you for this! You just saved me a lot of time. You could add to your answer the link to the EWS Java API documentation: https://github.com/OfficeDev/ews-java-api/wiki/Getting-Started-Guide – Spenhouet Nov 13 '17 at 12:26
-
@Spen, thank you too. i have add it to the EWS Java API documentation's Common Issues. pls help me check it and tell me whether it's correct. – Python Basketball Nov 15 '17 at 05:39
-
@Dang Oh I meant to add a link of the documentation to this stackoverflow answer. – Spenhouet Nov 15 '17 at 12:04
-
@Dang Yes, perfect :) – Spenhouet Nov 15 '17 at 13:11
-
@Spen, i have a question, did you use Spring Cloud? – Python Basketball Nov 15 '17 at 13:25
-
@Dang No, sorry. I'm using the Play Framework deployed on Google Cloud. – Spenhouet Nov 15 '17 at 13:58
-
Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/159140/discussion-between-dang-and-spen). – Python Basketball Nov 16 '17 at 10:16
-
microsoft.exchange.webservices.data.core.exception.service.remote.ServiceRequestException: The request failed. The request failed. sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target Seeing this error . How to get around this? – Katakam Nikhil Feb 27 '20 at 22:16
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) {}
}

- 1,082,665
- 372
- 3,610
- 3,555
-
Thanks for your answer. I'm using the same username and password with my outlook and is working. Exception in thread "main" javax.mail.MessagingException: Could not connect to SMTP host: XXX.XXX.XXX.XXX, port: 2525; nested exception: java.net.ConnectException: Connection timed out: connect at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1545) at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:453) at javax.mail.Service.connect(Service.java:291) at javax.mail.Service.connect(Service.java:172) at javax.mail.Service.connect(Service.java:192) any idea? – rafaochoa Nov 16 '09 at 20:25
-
You need to change the port number to the actual port number of the server. It's usually 25, but it can be different. Consult mailserver's admin for details. Sorry for not mentioning that in the message, I thought it'd be obvious enough. – BalusC Nov 16 '09 at 21:03
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.

- 29,904
- 14
- 93
- 125
-
Thanks for your answer. I don't understand your code could you comment your code or something? – rafaochoa Nov 16 '09 at 20:26
Microsoft released an open sourced API for connecting to Exchange Web Service

- 7,470
- 3
- 38
- 54
-
-
-
Seeing this error. Some SSL certificate not present?? Is there a way to get around it? microsoft.exchange.webservices.data.core.exception.service.remote.ServiceRequestException: The request failed. The request failed. sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target – Katakam Nikhil Feb 27 '20 at 22:14
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.

- 11,935
- 4
- 61
- 87

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

- 6,951
- 4
- 57
- 77

- 2,251
- 21
- 34
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.

- 2,445
- 2
- 25
- 15
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/

- 75
- 9
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+

- 76
- 6