Javamail ignores specified SMTP port for Gmail connection

Hey everyone,

I’m stuck with a Javamail issue in my Groovy script. I’m trying to send emails through Gmail’s SMTP server, but it’s not working as expected.

The weird thing is, even though I set the port to 587, the debug output shows it’s trying to use port 25. Here’s the error I’m getting:

DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 25, isSSL false
Caught: javax.mail.SendFailedException: Send failure (javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25 (javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?))

I’ve checked that port 587 works with telnet and Thunderbird, so it’s not a connectivity issue.

Has anyone run into this before? Any ideas on why Javamail might be ignoring the port setting? I’ve tried different SSL settings too, but no luck.

I can share my code if needed, but it’s pretty standard Javamail setup with Gmail SMTP properties.

Thanks for any help!

I’ve encountered a similar issue before, and it turned out to be related to how the properties were being set. Make sure you’re using ‘mail.smtp.port’ instead of just ‘smtp.port’ in your properties. Also, double-check that you’re using ‘mail.smtp.starttls.enable=true’ for Gmail’s SMTP.

If that doesn’t work, try explicitly setting the transport protocol:

properties.setProperty(‘mail.transport.protocol’, ‘smtp’)

Another thing to consider is whether you’re creating the Session object correctly. Sometimes, if the properties aren’t applied properly to the Session, it can fall back to default settings.

Lastly, ensure you’re not accidentally overwriting your port setting somewhere else in your code. It’s easy to miss, especially in larger scripts.

I’ve been down this rabbit hole before, mate. The trick that worked for me was using SSL instead of TLS for Gmail. Try setting ‘mail.smtp.socketFactory.port’ to 465 and ‘mail.smtp.socketFactory.class’ to ‘javax.net.ssl.SSLSocketFactory’. Also, make sure ‘mail.smtp.auth’ is set to true.

If that doesn’t do it, check if you’re using the latest version of JavaMail. Older versions can be finicky with Gmail’s security updates.

One last thing - if you’re using app passwords (which you should be), double-check that it’s correctly entered. A typo there can cause all sorts of weird behavior.

Let us know if any of this helps. Debugging SMTP issues can be a real pain in the neck!

hey dave, i’ve had a similar issue. try usin ‘mail.smtp.port’ not ‘smtp.port’ and set ‘mail.smtp.starttls.enable=true’. if that don’t work, set protocol via properties.setProperty(‘mail.transport.protocol’,‘smtp’). hope this helps!