eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

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.

Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)
guest
0 Comments
Oldest
Newest
Inline Feedbacks
View all comments