Gmail SMTP connection getting dropped when sending multiple emails via JavaMail API

I’m working with a Message Driven Bean that handles email sending. Each time my bean processes a message, it needs to send up to 10 emails. My approach is to establish a single SMTP connection to Gmail and reuse it for all the emails in that batch.

However, I keep running into issues where the connection gets terminated unexpectedly. Here’s the error I’m seeing:

javax.mail.MessagingException: Unable to send command to SMTP server; nested exception is:
java.net.SocketException: Remote host closed connection at
com.sun.mail.smtp.SMTPTransport.executeCommand(SMTPTransport.java:1901) at
com.sun.mail.smtp.SMTPTransport.executeCommand(SMTPTransport.java:1888) at
com.sun.mail.smtp.SMTPTransport.terminate(SMTPTransport.java:996) at
javax.mail.Transport.send0(Transport.java:216) at
javax.mail.Transport.send(Transport.java:143) at
...

I’m wondering if Gmail’s servers are interpreting my email pattern as suspicious activity and dropping the connection as a spam prevention measure. I understand there’s a limit of 10 concurrent connections to Gmail SMTP, but this feels like a different issue altogether. Would implementing a connection pool strategy resolve this problem, or should I be looking at other solutions?

Gmail’s SMTP server tends to drop idle connections after short periods of inactivity, which can be problematic when sending multiple emails. Each send may experience slight delays, leading to connection termination. I recommend implementing a retry mechanism with exponential backoff. This involves establishing a new connection for each email, and if a send fails, waiting progressively longer before trying again. This approach effectively manages connection drops and maintains reasonable throughput. Avoid connection pooling, as Gmail does not favor persistent connections.

sounds like gmail’s rate limiting is a prob. try adding small delays like 1-2 secs between sends instead of sending em all at once. also, don’t forget to close the transport conn properly after each batch, otherwise it could trigger spam filters!

I encountered a similar issue while developing a bulk email feature. The problem isn’t solely due to Gmail’s spam filter but rather how JavaMail handles SMTP timeouts. To resolve this, I suggest configuring the mail.smtp.connectionpoolsize to 1 and setting the mail.smtp.connectionpooltimeout to 300000 milliseconds. Additionally, if possible, enable mail.smtp.auth.mechanisms with XOAUTH2 for better authentication management. Instead of sending all 10 emails at once, consider batching them into groups of 3-5 to stay within Gmail’s undocumented rate limits.