I’m working on a Groovy script that sends emails through Gmail’s SMTP server using JavaMail. The issue is that my application keeps trying to connect on port 25 even though I’ve configured it to use port 587.
Here’s the error message I’m getting:
DEBUG SMTP: useEhlo true, useAuth false
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 verified that port 587 works fine with other email clients like Thunderbird using STARTTLS. Here’s my current implementation:
import javax.mail.*
import javax.mail.internet.*
private class EmailAuthenticator extends Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication('[email protected]', 'mypassword')
}
}
def userEmail = "[email protected]"
def userPassword = "mypassword"
def smtpHost = "smtp.gmail.com"
def smtpPort = "587"
def recipientEmail = "[email protected]"
def emailSubject = "Test Message"
def emailBody = "Hello, this is a test email."
def properties = new Properties()
properties.put("mail.smtp.user", userEmail)
properties.put("mail.smtp.host", smtpHost)
properties.put("mail.smtp.port", smtpPort)
properties.put("mail.smtp.starttls.enable", "true")
properties.put("mail.smtp.debug", "true")
properties.put("mail.smtp.auth", "true")
properties.put("mail.smtp.socketFactory.port", smtpPort)
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory")
properties.put("mail.smtp.socketFactory.fallback", "false")
def authenticator = new EmailAuthenticator()
def mailSession = Session.getInstance(properties, authenticator)
mailSession.setDebug(true)
def message = new MimeMessage(mailSession)
message.setText(emailBody)
message.setSubject(emailSubject)
message.setFrom(new InternetAddress(userEmail))
message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipientEmail))
Transport.send(message)
What could be causing JavaMail to ignore my port configuration and default to port 25? Any suggestions would be really helpful!