Gmail SMTP connection keeps getting dropped during JavaMail email sending

I’m working with a Message Driven Bean that handles email delivery whenever it receives a message. For each message, I need to send up to 10 emails maximum. My approach is to establish a single SMTP connection to Gmail and use it for all the emails in that batch.

However, I keep running into this annoying issue where the connection gets terminated randomly. Here’s the error I’m seeing:

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) at
com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:1865) at
com.sun.mail.smtp.SMTPTransport.close(SMTPTransport.java:973) at
javax.mail.Transport.send0(Transport.java:193) at
javax.mail.Transport.send(Transport.java:120)

I’m wondering if Gmail’s spam detection is kicking in and terminating my connection. I know they have a limit of 10 concurrent connections, but this feels like a different issue altogether. Would implementing a connection pool be a better solution for this problem?

same issue here with gmail smtp. set mail.smtp.ssl.protocols to “tlsv1.2” - gmail’s been rejecting older tls versions. those connection drops could be ur firewall killing idle connections, not just gmail.

I encountered a similar problem with Gmail SMTP while sending multiple emails. It’s not just spam detection that causes these drops; often, it’s due to Gmail’s strict timeout settings. They close idle connections quickly, which can be problematic when sending messages in quick succession. Instead of relying on a single connection, consider initiating a new connection for every few emails to maintain reliability. Adjusting the timeout settings—like setting mail.smtp.timeout and mail.smtp.connectiontimeout to something higher, such as 30000ms—can also help reduce your connection drops. While connection pooling is an option, it may complicate things unnecessarily for your use case of sending a maximum of 10 emails.

Gmail definitely has rate limiting that’s not well documented. I’ve hit this same issue when sending emails too fast through their SMTP servers. Those connection drops? They’re usually from hitting their hidden rate limits, not the concurrent connection limit you’re thinking of. Adding a 1-2 second delay between sends has fixed this for me almost every time. Also, check your auth method - if you’re still using basic auth instead of OAuth2, Gmail gets way more aggressive about killing connections. I’d try retry logic with exponential backoff first before messing with connection pooling. That just adds complexity without fixing Gmail’s actual rate limiting.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.