2026-07-15

javax.mail.internet.AddressException: Illegal address in string ``''

Stefan Bogdanescu

Stefan Bogdanescu

Founder & Senior Architect

javax.mail.internet.AddressException: Illegal address in string ``''

Decoding the Mail Error: Solving javax.mail.internet.AddressException: Illegal address in string ``''

As senior developers, we often deal with frustrating runtime errors that seem obscure but stem from fundamental data handling issues. One such common hurdle is sending emails using JavaMail APIs, where subtle errors in string formatting can halt the entire process. Today, we are diving deep into a specific and notorious error: javax.mail.internet.AddressException: Illegal address in string ``''.

If you’ve been attempting to send emails programmatically—especially when dealing with usernames and email addresses retrieved from a database—this error is a clear signal that the address string you are feeding into the InternetAddress constructor is malformed, even if it appears correct at first glance.

Understanding the Root Cause of the AddressException

The error message Illegal address in string ``'' occurs deep within the JavaMail library when it attempts to parse a string into a valid email address format using the InternetAddress class. The core issue is not necessarily that the email exists, but that the string format violates the rules expected by the underlying mail protocol standards (RFCs).

In your provided code snippets, the problem likely lies in the variables userName or toAddress. Even if they look like standard emails, they might contain extraneous whitespace, incorrect characters, or improperly escaped special characters that confuse the parser.

Let's examine where this happens in your utility method:

msg.setFrom(new InternetAddress(userName));
InternetAddress[] toAddresses = { new InternetAddress(toAddress) }; // <- Error likely occurs here if toAddress is bad
msg.setRecipients(Message.RecipientType.TO, toAddresses);

The InternetAddress constructor is very strict. It expects a properly formatted address (e.g., user@domain.com). If your database retrieved an address that included leading/trailing spaces or illegal characters, the constructor throws this exception.

Practical Solutions and Code Refinements

To resolve this, we must implement robust input validation and sanitization before attempting to create the InternetAddress objects. This is a critical practice in any application, whether you are building APIs using frameworks like Laravel or handling sensitive data in Java backend systems.

1. Input Sanitization: Trimming Whitespace

The simplest and most common fix is to ensure that no extraneous whitespace exists around your email strings. Always use the trim() method immediately after retrieving data from the database.

Before (Potentially Faulty):

msg.setFrom(new InternetAddress(userName)); // If userName is " user@example.com ", this fails!
InternetAddress[] toAddresses = { new InternetAddress(toAddress) };

After (Robust Fix):

String cleanUserName = userName.trim();
String cleanToAddress = toAddress.trim();

// Validate that the strings are not empty after trimming
if (cleanUserName.isEmpty() || cleanToAddress.isEmpty()) {
    throw new IllegalArgumentException("Email address cannot be empty.");
}

msg.setFrom(new InternetAddress(cleanUserName));
InternetAddress[] toAddresses = { new InternetAddress(cleanToAddress) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);

2. Comprehensive Validation (The Senior Developer Approach)

As a senior developer, we don't just fix the immediate error; we anticipate future failures. We should validate that the string actually looks like an email address using regular expressions before constructing the InternetAddress object. This prevents malformed attempts from reaching the mail client entirely.

You can use Java's Pattern and Matcher classes for this validation:

import java.util.regex.Pattern;

// ... inside your EmailUtility class ...

private static final Pattern EMAIL_PATTERN = 
    Pattern.compile("^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}$");

public void sendEmail(String host, String port, String user, String pass, 
                     String email, String subject, String message) throws Exception {
    
    // Input validation step
    if (!EMAIL_PATTERN.matcher(email).matches()) {
        throw new IllegalArgumentException("Invalid email format provided: " + email);
    }

    Message msg = new MimeMessage(session);
    
    // Now, safely construct the address
    msg.setFrom(new InternetAddress(email.trim())); 
    InternetAddress[] toAddresses = { new InternetAddress(email.trim()) };
    msg.setRecipients(Message.RecipientType.TO, toAddresses);
    
    // ... rest of the sending logic
}

By implementing this validation layer, you ensure that only syntactically correct email strings are ever passed to the sensitive InternetAddress constructor, making your system far more resilient. This principle of strict input validation is central to building secure and reliable applications, much like adhering to best practices when structuring data in systems like those found in Laravel.

Conclusion

The error javax.mail.internet.AddressException: Illegal address in string ``'' is a classic symptom of poor input handling during address construction. By moving beyond simple checks and implementing rigorous sanitization (using trim()) combined with formal pattern matching (Regex validation), you transform a frustrating runtime failure into a handled, predictable exception. Always treat external input—especially data used for system operations like email delivery—with the utmost skepticism and validation.

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.