I’m trying to send emails through Gmail SMTP in my Java web application but keep running into an ArrayIndexOutOfBoundsException. The weird thing is that it worked fine initially and I managed to send a few test emails successfully. After making some modifications to fit my project requirements, it started throwing this error.
package com.example.notification;
import java.security.Security;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class EmailSender {
private static final String GMAIL_HOST = "smtp.gmail.com";
private static final String GMAIL_PORT = "465";
private static final String SENDER_EMAIL = "[email protected]";
private static final String SSL_FACTORY_CLASS = "javax.net.ssl.SSLSocketFactory";
public static void sendNotification(String[] recipients, String subject, String content) throws Exception {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
new EmailSender().sendSecureEmail(recipients, subject, content, SENDER_EMAIL);
System.out.println("Email sent successfully to all recipients");
}
public void sendSecureEmail(String[] toAddresses, String emailSubject, String emailContent, String fromAddress) throws MessagingException {
Properties mailProps = new Properties();
mailProps.put("mail.smtp.host", GMAIL_HOST);
mailProps.put("mail.smtp.auth", "true");
mailProps.put("mail.debug", "true");
mailProps.put("mail.smtp.port", GMAIL_PORT);
mailProps.put("mail.smtp.socketFactory.port", GMAIL_PORT);
mailProps.put("mail.smtp.socketFactory.class", SSL_FACTORY_CLASS);
mailProps.put("mail.smtp.socketFactory.fallback", "false");
Session mailSession = Session.getDefaultInstance(mailProps, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("[email protected]", "mypassword123");
}
});
MimeMessage emailMessage = new MimeMessage(mailSession);
emailMessage.setFrom(new InternetAddress(fromAddress));
for(int i = 0; i <= toAddresses.length; i++) {
emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddresses[i]));
}
emailMessage.setSubject(emailSubject);
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText(emailContent);
Multipart multipartContent = new MimeMultipart();
multipartContent.addBodyPart(textPart);
emailMessage.setContent(multipartContent);
Transport.send(emailMessage);
}
}
I call this from my JSP page like this:
<%
String action = request.getParameter("action");
if("Reserve".equalsIgnoreCase(action)) {
String[] emailList = {"[email protected]", "[email protected]"};
EmailSender.sendNotification(emailList, "Book Reservation Alert", "A book has been reserved by user");
}
%>
The error I’m getting shows ArrayIndexOutOfBoundsException at index 2, which seems to be related to the email recipient array. Can anyone spot what’s wrong with my loop or array handling?
The Problem: You’re encountering an ArrayIndexOutOfBoundsException when sending emails using your Java application because of an off-by-one error in your for loop. The loop iterates one time too many, attempting to access an index that doesn’t exist in the toAddresses array.
TL;DR: The Quick Fix: Change the condition in your for loop from i <= toAddresses.length to i < toAddresses.length.
Understanding the “Why” (The Root Cause):
In Java (and most programming languages), arrays are zero-indexed. This means the first element is at index 0, the second at index 1, and so on. If you have an array with n elements, the valid indices range from 0 to n-1. Your original loop for(int i = 0; i <= toAddresses.length; i++) attempts to access an index equal to the length of the array. Since the highest valid index is length - 1, this causes an ArrayIndexOutOfBoundsException.
Step-by-Step Guide:
Correct the for loop: Open your EmailSender.java file and locate the sendSecureEmail method. Modify the for loop as follows:
for(int i = 0; i < toAddresses.length; i++) {
emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddresses[i]));
}
This change ensures the loop iterates only up to, but not including, the length of the toAddresses array, correctly handling all valid indices.
(Optional) Consider Enhanced for Loop: For enhanced readability and to prevent similar indexing errors in the future, consider rewriting the loop using Java’s enhanced for loop:
for (String recipient : toAddresses) {
emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
}
This approach iterates directly over the elements of the array without explicit index management, making the code more concise and less prone to off-by-one errors.
Recompile and Retest: After making these changes, recompile your Java code and thoroughly test your email sending functionality with various recipient lists.
Common Pitfalls & What to Check Next:
Hardcoded Credentials: Your code currently hardcodes the sender email and password directly within the Authenticator class. This is a major security risk. Immediately replace this with a more secure method of managing credentials, such as environment variables, a configuration file, or a dedicated secrets management system.
Error Handling: Your sendNotification method currently catches a generic Exception. For improved debugging and robustness, consider catching more specific exceptions (like MessagingException) and handling them appropriately, providing informative error messages to the user.
Gmail SMTP Settings: Double-check your Gmail SMTP settings, ensuring they are correctly configured for secure connections (using SSL/TLS on port 465 or 587). Refer to Google’s documentation for the most up-to-date guidelines.
Still running into issues? Share your (sanitized) config files, the exact command you ran, and any other relevant details. The community is here to help!
You’re getting ArrayIndexOutOfBoundsException because you’re using <= in your for loop. With an array of size 2, valid indices are 0 and 1 - but your loop tries to access index 2, which doesn’t exist. I hit the same issue last year with an email feature. Worked fine with one set of test recipients, then crashed with others. Just change your loop to for(int i = 0; i < toAddresses.length; i++). Or use an enhanced for loop to avoid these indexing mistakes altogether.
Your loop’s going one index too far. You’re using i <= toAddresses.length which tries to access an index that doesn’t exist. Arrays start at 0, so a 2-element array has indices 0 and 1 - but your loop tries to hit index 2. Change it to i < toAddresses.length and you’re good. Had this exact same bug when I built a bulk email feature last year. Took me forever to spot such a simple off-by-one error. Also, try Session.getInstance() instead of getDefaultInstance() - it’ll save you headaches if you’re running multiple email sessions.
Found your bug right away - that for(int i = 0; i <= toAddresses.length; i++) line should be i < toAddresses.length instead of <=. You’re going one index too far, so it crashes trying to access toAddresses[2] when your array only goes 0,1
That array bug is classic. Everyone already covered the technical fix.
But building email functionality from scratch in Java? Total pain. You’re wrestling with SMTP configs, authentication, error handling, and JavaMail dependencies. Then there’s delivery rates, bounces, and spam filters to worry about.
I maintained similar code at work until I realized I was wasting time on email infrastructure instead of building actual features. Now I just automate email workflows through external services.
Latenode makes this dead simple. Set up email automation without the Java boilerplate - create a workflow that triggers on reservations, connects to your email service, sends to multiple recipients. No arrays to screw up, no SMTP headaches.
You get built-in error handling, retry logic, and monitoring. Way more reliable than rolling your own. Moved all our notification workflows there and haven’t looked back.