MailConnectException:无法连接到主机,端口:smtp.sendgrid.net

时间:2018-01-27 17:16:11

标签: java spring email smtp sendgrid

我为sendGrid创建了API密钥:

enter image description here

我有以下春季邮件配置:

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

我有以下代码:

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);

然后我尝试启动应用程序并体验以下错误:

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)

我该如何解决这个问题?

P.S。

端口587的所有内容都正确

但我想使用ssl并设置port = 465

spring.mail.port=465

在这种情况下,我的应用程序在启动时冻结。并且在打印5分钟后:

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)

我该如何避免这种情况?

3 个答案:

答案 0 :(得分:0)

您可能需要在配置中添加类似的内容。

spring.mail.smtp.ssl.enable=true

答案 1 :(得分:0)

您所在的国家/地区可能无法发现SendGrid SMTP服务器。尝试代理或VPN。

答案 2 :(得分:0)

我使用端口2525(非特权)而不是578(特权)来本地解决此问题。我仍然可以在云上使用特权用户。那解决了我的问题。