Enterprise Java

Sending Emails Through Microsoft Exchange Server

Microsoft Exchange Server is widely used in enterprise environments for managing emails, calendars, and contacts. Applications often need to send emails through an Exchange server for notifications, alerts, or reports. Let us delve into understanding how we can send an email using MS Exchange server in Java.

1. Understanding SMTP

SMTP (Simple Mail Transfer Protocol) – RFC 5321 is a traditional protocol used for sending emails by connecting directly to a mail server. In Microsoft ecosystems, SMTP is often compared with the Microsoft Graph API, which is a modern, REST-based approach for sending emails and accessing mailbox data.

1.1 Frequently Encountered Problems

  • Authentication Failed: This usually occurs when the username or password is incorrect, SMTP AUTH is disabled for the mailbox, or basic authentication is blocked at the tenant level.
  • STARTTLS Required: Exchange Online mandates encrypted connections. Ensure STARTTLS is enabled and port 587 is used.
  • Firewall Restrictions: Corporate firewalls or cloud network security groups may block outbound SMTP traffic, preventing the application from reaching the Exchange server.
  • Modern Authentication Enforced: Many newer Exchange tenants have basic authentication disabled, requiring OAuth-based solutions instead of username/password SMTP.

1.2 SMTP vs Microsoft Graph API

AspectSMTPMicrosoft Graph API
AuthenticationUsername & Password (Basic Auth or App Password)OAuth 2.0 with access tokens
SecurityLower, as Basic Auth is being deprecatedHigher, token-based and compliant with modern security standards
Setup ComplexitySimple setup with server, port, and credentialsRequires app registration, permissions, and token handling
Feature SupportLimited to sending emails onlySupports emails, attachments, calendar, users, mailboxes, and more
ScalabilityLess suitable for large-scale or enterprise workloadsDesigned for enterprise-scale and cloud-native applications
Future SupportLimited and gradually deprecated by MicrosoftActively supported and recommended by Microsoft
Use CaseLegacy systems or quick prototypesProduction-grade and secure enterprise integrations

2. Code Example

2.1 Prerequisites

Before implementing email functionality using Microsoft Exchange, ensure that the following prerequisites are met. Proper configuration at this stage helps avoid common runtime and authentication issues later.

  • Access to a Microsoft Exchange Server: This can be either:
    • On-premises Microsoft Exchange Server
    • Exchange Online (Microsoft 365 / Office 365)

    The mailbox used for sending emails must be active and allowed to send SMTP emails.

  • SMTP Configuration Details:
    • SMTP Host: Typically smtp.office365.com for Exchange Online. For on-premises Exchange, this will be your organization’s SMTP endpoint.
    • SMTP Port: Port 587 is recommended and requires STARTTLS encryption.
    • Authentication Credentials: A valid Exchange email address and password. Make note that some tenants require an app password or OAuth-based authentication if basic authentication is disabled.
  • Java Development Kit (JDK 8 or higher): Ensure the JDK is properly installed and available on the system path. The Jakarta Mail API is fully compatible with Java 8 and later versions.
  • JavaMail (Jakarta Mail) Dependency: Jakarta Mail provides the APIs required to construct and send emails using SMTP. It replaces the older javax.mail package.

If you are using Maven for dependency management, add the following dependency to your pom.xml file:

<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>jakarta.mail</artifactId>
    <version>stable__jar__version</version>
</dependency>

After adding the dependency, ensure that Maven downloads it successfully and that there are no version conflicts with other mail-related libraries in your project.

2.2 Java Code Example

The following example demonstrates how to send an email using Microsoft Exchange via SMTP from a Java application using the Jakarta Mail API.

// ExchangeEmailSender.java
import jakarta.mail.Message;
import jakarta.mail.MessagingException;
import jakarta.mail.PasswordAuthentication;
import jakarta.mail.Session;
import jakarta.mail.Transport;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;

import java.util.Properties;

public class ExchangeEmailSender {

    public static void main(String[] args) {

        // SMTP configuration
        String smtpHost = "smtp.office365.com";
        String smtpPort = "587";
        final String username = "your-email@yourdomain.com";
        final String password = "your-email-password";

        // Email details
        String toAddress = "recipient@domain.com";
        String subject = "Test Email from Java using MS Exchange";
        String emailBody = "Hello,\n\nThis email was sent using Microsoft Exchange SMTP.\n\nRegards,\nJava App";

        // Set SMTP properties
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.port", smtpPort);

        // Create mail session with authentication
        Session session = Session.getInstance(props, new jakarta.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        try {
            // Create the email message
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(username));
            message.setRecipients(
                    Message.RecipientType.TO,
                    InternetAddress.parse(toAddress)
            );
            message.setSubject(subject);
            message.setText(emailBody);

            // Send the email
            Transport.send(message);

            System.out.println("Email sent successfully!");

        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

2.2.1 Code Explanation

This Java program demonstrates how to send an email using a Microsoft Exchange SMTP server with the Jakarta Mail API. It begins by importing the required Jakarta Mail and Java utility classes, then defines SMTP connection details such as the Exchange host (smtp.office365.com), TLS-enabled port (587), and valid Exchange credentials. The program specifies basic email metadata including the recipient address, subject, and message body. SMTP properties are configured to enable authentication and STARTTLS encryption, which are mandatory for Exchange Online. A mail Session is created using these properties along with an Authenticator that securely supplies the username and password at runtime. Within the try block, a MimeMessage object is constructed to represent the email, setting the sender, recipient, subject, and plain-text content. Finally, the Transport.send() method establishes a connection to the Exchange server and transmits the message, printing a success message upon completion, while any messaging or connectivity errors are caught and logged via the exception handler.

2.2.2 Code Output

When the program is executed, the output depends on whether the email is sent successfully or an error occurs during the SMTP communication with the Microsoft Exchange server.

Email sent successfully!

This output indicates that the application successfully authenticated with the Exchange SMTP server, established a secure TLS connection, and delivered the email to the recipient’s mailbox without any issues.

jakarta.mail.AuthenticationFailedException: 535 5.7.3 Authentication unsuccessful
    at jakarta.mail.Transport.send(Transport.java:...)
    at ExchangeEmailSender.main(ExchangeEmailSender.java:...)

This error output occurs when the SMTP server rejects the authentication request. Common causes include incorrect credentials, SMTP AUTH being disabled for the mailbox, or basic authentication being blocked by the Exchange tenant. Other possible errors may include network connectivity issues, TLS misconfiguration, or firewall restrictions. The stack trace helps identify the root cause and should be reviewed carefully during troubleshooting.

3. Conclusion

Sending emails using Microsoft Exchange via SMTP in Java is straightforward and suitable for many legacy and internal applications. By using the Jakarta Mail API, you can quickly integrate email functionality with minimal configuration. However, for new applications or cloud-first architectures, Microsoft Graph API offers better security, scalability, and long-term support. Choosing the right approach depends on your organization’s security policies and application requirements.

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Back to top button