I’m working on a Groovy application that needs to send emails through Gmail’s SMTP service using Javamail. Even though I configure it to use port 587, the connection attempts keep defaulting to port 25.
Error message I keep seeing:
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)
My current implementation:
import javax.mail.*
import javax.mail.internet.*
class GmailAuthenticator extends Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication('[email protected]', 'mypassword')
}
}
def emailConfig = [
user: "[email protected]",
pass: "mypassword",
server: "smtp.gmail.com",
portNum: "587",
recipient: "[email protected]",
subject: "Test Email",
content: "Hello from Groovy"
]
def mailProps = new Properties()
mailProps.put("mail.smtp.user", emailConfig.user)
mailProps.put("mail.smtp.host", emailConfig.server)
mailProps.put("mail.smtp.port", emailConfig.portNum)
mailProps.put("mail.smtp.starttls.enable", "true")
mailProps.put("mail.smtp.debug", "true")
mailProps.put("mail.smtp.auth", "true")
mailProps.put("mail.smtp.socketFactory.port", emailConfig.portNum)
mailProps.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory")
mailProps.put("mail.smtp.socketFactory.fallback", "false")
def authenticator = new GmailAuthenticator()
def mailSession = Session.getInstance(mailProps, authenticator)
mailSession.setDebug(true)
def message = new MimeMessage(mailSession)
message.setText(emailConfig.content)
message.setSubject(emailConfig.subject)
message.setFrom(new InternetAddress(emailConfig.user))
message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailConfig.recipient))
Transport.send(message)
I can connect to Gmail SMTP on port 587 using other email clients without issues. What configuration am I missing that would force Javamail to respect the specified port number?