I’m running into a problem with my Message Driven Bean that sends emails through Gmail using JavaMail. The bean opens one connection to Gmail and tries to send multiple emails (less than 10) per message it receives. But sometimes I get a MessagingException during Transport.send().
The error says the connection was closed by the remote host. Here’s a snippet of the stack trace:
javax.mail.MessagingException: Can't send command to SMTP host;
nested exception is: java.net.SocketException: Connection closed by remote host
at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:1878)
// ... more lines ...
I’m wondering if Gmail is closing the connection because it thinks it’s spam. Or maybe it’s related to Gmail’s limit on concurrent connections? Would using a connection pool help solve this issue? Any ideas on how to make this more reliable?
hey there! i’ve dealt with similar issues before. gmail can be finicky with multiple sends. have u tried implementing exponential backoff and retry? that helped me alot. also, using a connection pool might help maintain stable connections. good luck with ur project!
In my experience working with JavaMail and Gmail, connection issues are often linked to Gmail’s stringent anti-spam policies. When a connection is maintained for multiple sends, the server might interpret the rapid activity as suspicious. I addressed this by employing connection pooling, which ensured that each SMTP connection was given time to stabilize before the next message was sent. Additionally, introducing a brief pause between sends helped maintain connection integrity. Switching to OAuth 2.0 for authentication also contributed to a more reliable and secure email transmission process. These adjustments significantly reduced the frequency of connection closures.
I’ve encountered this exact issue in a production environment. What worked for us was implementing a session-per-send approach instead of reusing the same connection. We’d create a new Session object for each email, which helped avoid Gmail’s connection limits.
Also, we found that adding a small delay (around 1-2 seconds) between sends significantly reduced these errors. It’s not ideal for high-volume scenarios, but it worked well for our use case of <10 emails per batch.
If you need to stick with a single connection, you might want to look into using Gmail’s XOAUTH2 authentication method. It’s more robust and less likely to trigger anti-spam measures.
Lastly, make sure you’re not hitting Gmail’s sending limits. They have daily and per-minute restrictions that can cause connection issues if exceeded.