MailConnectException: Could not connect to host, port: smtp.sendgrid.net

I created an API key for sendGrid:

enter image description here

I have the following spring mail configuration:

spring.mail.default-encoding=UTF-8
spring.mail.host=smtp.sendgrid.net
spring.mail.username=apikey
spring.mail.password=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
spring.mail.port=25
spring.mail.protocol=smtp
spring.mail.test-connection=true

And I have the following code:

MimeMessage message = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message,
            MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,
            StandardCharsets.UTF_8.name());
Template template = freemarkerConfig.getTemplate(templateFileName);
String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, props);

helper.setTo("myEmail@gmail.com");
helper.setText(html, true);
helper.setSubject(subject);
helper.setFrom(from);
sender.send(message);
logger.debug("Send email to {} with subject: [{}]", Arrays.toString(to), subject);

Then I try to run the application and experience the following error:

27.01.18 20:07:20.460 [main] WARN  c.d.m.s.c.MailSenderValidatorAutoConfiguration - Mail server is not available
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.sendgrid.net, 25; timeout -1
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2118)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:712)
    at javax.mail.Service.connect(Service.java:366)
    at org.springframework.mail.javamail.JavaMailSenderImpl.connectTransport(JavaMailSenderImpl.java:501)
    at org.springframework.mail.javamail.JavaMailSenderImpl.testConnection(JavaMailSenderImpl.java:382)

How can i fix this?

PS

Everything is true for port 587

But I want to use ssl and set port = 465

spring.mail.port=465

And in this case, my application freezes at startup. After 5 minutes it prints:

27.01.18 21:06:05.960 [main] WARN  c.d.m.s.c.MailSenderValidatorAutoConfiguration - Mail server is not available
javax.mail.MessagingException: Could not connect to SMTP host: smtp.sendgrid.net, port: 465, response: -1
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2106)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:712)
    at javax.mail.Service.connect(Service.java:366)
    at org.springframework.mail.javamail.JavaMailSenderImpl.connectTransport(JavaMailSenderImpl.java:501)
    at org.springframework.mail.javamail.JavaMailSenderImpl.testConnection(JavaMailSenderImpl.java:382)

How can i avoid this?

+1
source share
3 answers

You may need to add something similar to your configuration.

spring.mail.smtp.ssl.enable=true
0
source

, SMTP- SendGrid . VPN.

0

I used port 2525 (unprivileged) instead of 578 (privileged) to solve the problem locally. I can still use privileged in the cloud. This solved my problem.

0
source

All Articles