Let's get started with a Microservice Architecture with Spring Cloud:
How to Send an Email Using MS Exchange Server
Last updated: January 28, 2026
1. Introduction
Sending emails is very common in enterprise Java applications. Some of the use cases include sending transactional emails, sending a notification, or sharing important updates.
In this article, we’ll explore how to configure and send emails programmatically using MS Exchange Server in Java. We’ll also explore common issues we encounter and alternative solutions.
2. Prerequisites
In this section, we’ll look at the prerequisites for sending emails using Exchange Server.
2.1. SMTP Properties
Before we start writing code, we need to ensure that we have an SMTP hostname, an SMTP port, and a valid Exchange username and password. In addition, we also need to know the port number to access the server. Typically, it’d be either port 25 or port 587.
2.2. Required Libraries
Java doesn’t have native support to send emails. We need jakarta.mail-api (formerly JavaMail) to send emails, and angus-mail is the actual SMTP implementation required at runtime. Without this, we’ll get provider or transport errors.
Let’s add the Maven dependencies:
<dependency>
<groupId>jakarta.mail</groupId>
<artifactId>jakarta.mail-api</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>org.eclipse.angus</groupId>
<artifactId>angus-mail</artifactId>
<version>2.0.3</version>
</dependency>
3. Java Code Example
In this section, we’ll explore how to access MS Exchange through Java code and send emails.
3.1. Setting SMTP Properties
To send Emails through Exchange, we need to configure SMTP properties. These properties tell Java how to connect to the Exchange server.
Let’s start by introducing the properties:
Properties props = new Properties();
props.put("mail.smtp.host", "exchange.company.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth.mechanisms", "LOGIN");
The mail.smtp.host specifies the host where the SMTP commands need to be sent.
Next, mail.smtp.port specifies the port where the server accepts SMTP connections. Here, we used port 587, which is the standard port that requires authentication. Usually, the Exchange server doesn’t allow communication through port 25 for security reasons.
Next, we set mail.smtp.auth to true, which tells JavaMail that authentication is required before it attempts to send mail.
The mail.smtp.starttls.enable property enables STARTTLS, which upgrades the initial plain connection to an encrypted TLS channel. This ensures that the credentials and email content are protected in transit.
Finally, mail.smtp.auth.mechanisms is set to LOGIN. This’ll tell JavaMail to use LOGIN as the authentication mechanism, using a username and password.
3.2. Creating Mail Session
Next, we need to create a mail session. The session holds SMTP configuration and authentication details to send the email:
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
A session in Jakarta Mail helps create context with the necessary configurations to communicate with the mail server. With Session.getInstance, we’re creating a new session using the SMTP properties.
The second argument we’ve passed is an anonymous subclass of Authenticator. Instead of hardcoding the credentials, JavaMail asks the Authenticator for credentials only when the server requests them during the SMTP handshake.
Next, when the Exchange Server sends an authentication challenge, JavaMail calls the getPasswordAuthentication method to retrieve the credentials.
3.3. Composing Email
Let’s now see how we can programmatically compose the email and send :
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(FROM_ADDRESS));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
message.setSubject(subject);
message.setText(body);
The session object contains all SMTP configurations. It creates the MimeMessage object, which represents the email message to be sent. It has a subject, body, recipients, and headers.
The setFrom() method sets the sender’s email. This is the address that’s seen in the from field when the email is sent. This must match the email account configured in the Exchange server.
The setRecipients() method sets the receiver’s email, to which the email must be sent. Here, Message.RecipientType.TO specifies primary recipients and Internet addresses, and parse safely converts the recipient string into one or more valid email address objects.
The setSubject() method sets the email subject, and setText() sets the email body content as plain text.
3.4. Sending Email
Let’s write the code to send an email to the receiver:
Transport.send(message);
System.out.println("Email sent successfully");
The statement Transport.send(message) provides the fully constructed email to JavaMail’s SMTP transport. This connects to the SMTP server and sends the message. If we don’t have any exceptions, the mail is successfully sent.
3.5. Debugging and Logging Smtp Communication
We often rely on exception messages to determine the cause of the failure. However, sometimes it’s hard to determine the problem purely based on the exception message. With Jakarta Mail, we’d be able to log the complete SMTP conversation, TLS negotiations, and server responses. We can see them by enabling the Jakarta Debug logging:
session.setDebug(true);
After we enable debug logging, JavaMail prints detailed protocol-level information to the console. The output shows SMTP commands that the client sends and responses that the Exchange server returns. These logs help diagnose authentication failures, unsupported authentication mechanisms, and TLS-related problems.
It’s important to note that these logs would also print sensitive information like email addresses and authentication flow. Hence, we should only enable this during development or when troubleshooting and disable it in the production environment.
4. Common Issues
In this section, we’ll take a look at some of the common issues we come across during development.
4.1. Authentication Failure
Authentication failure commonly prevents mail from being sent. This occurs when the Exchange server rejects the credentials provided by the sending application.
To resolve this issue, administrators must enable SMTP authentication on the mail server and ensure that the credentials in use are valid.
Additionally, administrators need to confirm that they’ve selected the correct SMTP port and encryption method. Using an incorrect port or mismatched security settings, such as SSL/TLS or STARTTLS, can result in authentication errors.
4.2. Connection Errors
Connection errors occur when our application can’t establish a valid connection to the SMTP server. This is often caused by incorrect SMTP properties or network-related configurations.
To resolve this, we must ensure that the SMTP server address and port are configured correctly and that the sending system can reach the server. We also need to verify that the firewall rules or network security policies aren’t blocking outbound SMTP traffic.
Temporary server outages or disabled SMTP services can also lead to connection failures, so confirming server availability is important.
4.3. TLS and Certificate Issues
TLS certificate-related issues can also cause the mail delivery to fail. JVM doesn’t trust organizations’ self-signed certificates by default. This may cause JavaMail to throw SSL- or TLS-related exceptions even when the SMTP host and credentials are correct.
One solution is to import the Exchange server’s certificate into the JVM’s default trust store. Another approach is to use a custom trust store that contains the required certificates.
We can also disable certificate validation. However, this will significantly weaken security and may expose sensitive data.
5. SMTP vs Microsoft Graph API
SMTP offers an effective way to send emails with simple username and password authentication, making it ideal for on-premise Exchange servers and legacy systems. But it often comes with limitations.
SMTP access is restricted or disabled in some organizations. In these cases, we can’t use JavaMail. Instead, we must use alternatives like Microsoft Graph API or Exchange Web Services.
Microsoft Graph API uses OAuth-based authentication and is a recommended way to communicate with Exchange Server, as it improves security, gives more fine-grained control, and enables access to more advanced capabilities. They are more complex but officially supported for Exchange Online.
6. Conclusion
In this tutorial, we’ve seen that sending email programmatically using MS Exchange Server is similar to how we’d send email using any SMTP server. We’ve also looked at some of the common issues we might see while sending emails, and how to resolve them. While administrators typically use SMTP access for on-premises Exchange servers and legacy systems, they use the Microsoft Graph API for greater security in cloud-based Exchange Online deployments.
With the right configuration and settings, we can seamlessly send emails using the MS Exchange server.
As always, the source code for the examples can be found over on GitHub.















