2026-07-15

Send email using Java

Stefan Bogdanescu

Stefan Bogdanescu

Founder & Senior Architect

Send email using Java

Sending Emails with Java: Debugging SMTP Connection Errors

As a senior developer, I frequently encounter issues when dealing with external services like email delivery in backend applications. Sending emails via Java often involves using the javax.mail package, which provides a robust framework for interacting with SMTP servers. However, as you’ve experienced, connecting to an SMTP host can be deceptively simple on the surface but complex in practice.

This post will analyze the code snippet you provided, diagnose the connection error you encountered, and provide the corrected, production-ready approach for sending emails using Java.

The Problem: Why Your Email Sending Fails

You attempted to use the following configuration:

String host = "localhost";
// ... setup properties based on localhost and port 25

And you received the error: Connection refused: connect.

This error is not an issue with the Java code logic itself, but rather a fundamental problem with network connectivity and server configuration. Here is the breakdown from a developer's perspective:

  1. SMTP Server Misconfiguration: Port 25 is the default port for unencrypted SMTP (Simple Mail Transfer Protocol). While this port exists, most modern hosting providers, firewalls, and security policies actively block outbound connections on port 25 unless you are running a dedicated mail server.
  2. Localhost Limitation: Attempting to connect to localhost implies you expect the email server to be running on the same machine where your Java application is executing. Unless you have explicitly set up a local Mail Transfer Agent (MTA) like Postfix or Sendmail, this connection will almost always be refused because no service is listening there.
  3. Security and Authentication: Furthermore, sending emails reliably requires authentication (username and password). Simply connecting to an open port isn't enough; you need credentials to prove you are authorized to send mail through that server.

In short, your code failed because it tried to talk to a server that didn't exist or wasn't configured to accept external connections on that specific port. This is a common hurdle when moving from theoretical coding to real-world application deployment, much like setting up secure API endpoints in modern frameworks like those found within the Laravel ecosystem.

The Solution: Using External SMTP Services

To successfully send emails, you must configure your Java application to connect to a reliable, external Mail Transfer Agent (MTA) service, such as Gmail, SendGrid, or an internal corporate mail server. These services handle the complex routing and deliverability issues for you.

The best practice is to use a standard, secure port for SMTP communication. For secure connections (which is highly recommended), we typically use SMTPS on port 465 or STARTTLS on port 587.

Corrected Java Implementation Example

Here is how you should structure your code, assuming you are using an external service (we will use generic placeholders for credentials):

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class SendEmail {

    public static void main(String[] args) {

        // --- Configuration for an External SMTP Server (e.g., Gmail, SendGrid) ---
        String host = "smtp.gmail.com"; // Change this to your actual SMTP server host
        String port = "587";             // Standard port for STARTTLS/Submission
        String username = "your_email@example.com"; // Your full email address
        String password = "your_app_password";     // Use an App Password if using services like Gmail

        String to = "abcd@example.com";
        String from = username; // Sender address should match the SMTP login
        String subject = "Email Sent Successfully!";
        String text = "This email was sent successfully using Java Mail API.";

        try {
            // 1. Setup Session with Authentication
            Properties props = new Properties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.starttls.enable", "true"); // Enable STARTTLS for security
            props.put("mail.smtp.host", host);
            props.put("mail.smtp.port", port);

            Session session = Session.getInstance(props, new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });

            // 2. Create Message
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            message.setSubject(subject);
            message.setText(text);

            // 3. Send Message
            Transport.send(message);
            System.out.println("Email sent successfully to " + to);

        } catch (MessagingException e) {
            System.err.println("Error sending email:");
            e.printStackTrace();
        }
    }
}

Conclusion

The key takeaway is that network communication, especially for services like email delivery, requires precise configuration beyond just specifying a host and port. When working with Java networking, always anticipate the need for security protocols (like TLS/SSL) and proper authentication details when connecting to external servers. By switching from attempting to connect to localhost:25 to explicitly configuring an external SMTP server using secure ports (like 587), you move from a connection failure to a successful, reliable communication channel. Mastering these configuration details is crucial for building robust applications, whether you are developing backend systems in Java or architecting services with frameworks like Laravel.

Note: Blog content is currently available in English.

Tags:

Enhance your marketing setup with your own email marketing platform.

Join the growing number of SaaS platforms using Laravel Mail to offer email marketing solutions to their customers.