Javamailsender failed – com.sun.mail.util.MailConnectException:cannot connect to host,port with Java17 and SpringBoot 3.0.6 while using smtp hostname

huangapple go评论80阅读模式
英文:

Javamailsender failed - com.sun.mail.util.MailConnectException:cannot connect to host,port with Java17 and SpringBoot 3.0.6 while using smtp hostname

问题

我们正在尝试将Java服务从Java 11和SpringBoot 2.7.1迁移到Java 17和SpringBoot 3.0.6。

我们正在创建Docker镜像并部署到AWS Kubernetes(1.24)。在Java 11和SpringBoot 2.7.1下,可以成功触发电子邮件,但在升级后,我们在SMTP主机名处遇到以下错误。

注意:如果我们提供SMTP服务器的IP地址,使用Java 17和SpringBoot 3.0.6时,代码可以正常工作。

在本地机器上,从IDE中,我们能够使用Java和SpringBoot版本的主机名和IP地址成功触发电子邮件。

12:46:48 DEBUG SMTP: trying to connect to host "company smpt host", port 25, isSSL false
12:46:48 ("timestamp":"07-03-2823 GMT 67:14:19.672","level": "ERROR", "thread":"http-nio-8081-exec- 6", "logger":"com.emailer.service.FreeMarkerEMailSevice","message":"Email sending failed with execption :
{}","context":"default","exception":"com.sun.mail.util.MailConnectException: Couldn't connect to host, port: <company.smtpserver.com>, 5000\n\tat com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2259)\n\tat com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:754)\n\tat jakarta.mail.Service.connect(Service.java:342)\n\ta org.springframework.mail.javamail.JavaMailSenderImpl.connectTransport (JavaMailSenderImpl.java:518)\n\tat
org.springframework ail.jovanail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:437)\n\tat
org.springfra ork.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:361)\n\tat org.springframework.mail.javanail. JavaMailSenderImpl.send(JavaMailSenderImpl.java:356)\n\tat
.
..
...

java.net.UnknownHostException: <company smtp host>\n\tat java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:567)\n\tat java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:331)\n\tat java.base/java.net.Socket.connect(Socket.java:630)\n\tat
com.sun.mail.util.WriteTimeoutSocket.connect(WriteTimeoutSocket.java:104)\n\tat
com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:355)

Application.yaml

spring.mail.host = <company smtpserver>
spring.mail.port= 25
spring.mail.username = xxxxx
spring.mail.password = xxxx
spring.mail.properties.mail.smtp.auth = true;
spring.mail.properties.mail.smtp.starttls.enable = true
spring.mail.properties.mail.transport.protocol = smtp
spring.mail.properties.mail.smtp.timeout = 5000

Java代码:

@Service
public class EmailService {

 private JavaMailSender emailSender;

 public EmailService(JavaMailSender emailSender){
   this.emailSender = emailSender;
 }
 
 @Override
 public void sendEmail(MailModel mailModel) {
     MimeMessage message = emailSender.createMimeMessage();
     try{
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(message,true);
       
        Template template = emailConfig.getTemplate("email4.ftl");
        String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, mailModel.getModel());
        mimeMessageHelper.setTo(mailModel.getTo());
        mimeMessageHelper.setText(html, true);
        mimeMessageHelper.setSubject(mailModel.getSubject());
        mimeMessageHelper.setFrom(mailModel.getFrom());

        emailSender.send(mimeMessageHelper.getMimeMessage());
    }catch(Exception e){
        log.error("exception occurred {}", e.getCause());
    }
 }
}

我们尝试使用inetaddress调试代码,也出现了错误。

InetAddress address = null;
try{
 address = InetAddress.getByName(hostname);
} catch(UnknownHostException e){
   log.error("error occurred while trying to get ipaddress : {}, hostname);
   throw new RuntimeException(e);
}

错误堆栈:

12:45:48 ("timestamp":"87-03-2023 GHT 07:16:35.225","level":"ERROR","thread":"http-nio-8881-exec-
7","logger":"com.emailer.service.FreeMarkerEMailSevice","message":"error occurred while trying to get ipaddress <company smtp server> text":"default")
12:46:48 {"timestamp":"07-03-2023 GT 07:16:35.226","level":"ERROR","thread":"http-nio-8881-exec-
7","logger":"org.apache.catalina.core.ContainerBase. [Tomcat].[localhost].[/].[dispatcherServlet]","message":"Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: java.lang.RuntimeException: java.net.UnknownHostException <company smtp server>: Try again) with root cause","context":"default","exception":"java.net.UnknownHostException: <company smtp server>: Try again\n\ java.base/java.net.InetAddressImpl.lookupAllHostAddr(Native Method)\n\tat
java.base/java.net.InetAddress.PlatformameService.lookupAllHostAddr(InetAddress.java:932)\n\tat
java.base/java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1517)\n\tat
java.base/java.net.InetAdd eServiceAddresses.get(InetAddress.java:851)\n\tat
java.base/java.net.InetAddress.getAllByName0(InetAddress.java:1587)\n\tat java.base/java.net.InetAddress.getAllByName(InetAddress.java:1366)\n\t
java.base/java.net.InetAddress.getAllByName(InetAddress.java:1300)\n\tat java.base/java.net.InetAddress.getByName(InetAddress.java:1250)\n\tat

我们尝试将其编译成一个jar文件,并在AWS VM中使用主机名和Java 17运行它,成功触发了电子邮件。

英文:

We are trying to migrate Java service from java 11 and SpringBoot 2.7.1 to Java 17 and SpringBoot 3.0.6.

we are creating the docker image and deploying to AWS kubernates (1.24). with java 11 and SpringBoot 2.7.1, able to trigger email successfully but after upgrade, we are getting below error with the smtp hostname.

Note: if we give the ip address of that smtp server, code works fine with java 17 and SpringBoot 3.0.6.

in local machine, from IDE, we were able to trigger an email with hostname as well as ipaddress from both java and SpringBoot version

12:46:48 DEBUG SMTP: trying to connect to host &quot;company smpt host&quot;, port 25, isSSL false
12:46:48 (&quot;timestamp&quot;:&quot;07-03-2823 GMT 67:14:19.672&quot;,&quot;level&quot;: &quot;ERROR&quot;, &quot;thread&quot;:&quot;http-nio-8081-exec- 6&quot;, &quot;logger&quot;:&quot;com.emailer.service.FreeMarkerEMailSevice&quot;, &quot;message&quot;:&quot;Email sending failed with execption :
{}&quot;,&quot;context&quot;:&quot;default&quot;, &quot;exception&quot;:&quot;com.sun.mail.util.MailConnectException: Couldn&#39;t connect to host, port: &lt;company.smtpserver.com&gt;,
5000\n\tat com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2259)\n\tat
com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:754)\n\tat jakarta.mail.Service.connect(Service.java:342)\n\ta org.springframework.mail.javamail.JavaMailSenderImpl.connectTransport (JavaMailSenderImpl.java:518)\n\tat
org.springframework ail.jovanail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:437)\n\tat
org.springfra ork.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:361)\n\tat org.springframework.mail.javanail. JavaMailSenderImpl.send(JavaMailSenderImpl.java:356)\n\tat
.
..
...

java.net.UnknownHostException: &lt;company smtp host&gt;\n\tat java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:567)\n\tat java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:331)\n\tat java.base/java.net.Socket.connect(Socket.java:630)\n\tat
com.sun.mail.util.WriteTimeoutSocket.connect(WriteTimeoutSocket.java:104)\n\tat
com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:355)

Application.yaml

spring.mail.host = &lt;company smtpserver&gt;
spring.mail.port= 25
spring.mail.username = xxxxx
spring.mail.password = xxxx
spring.mail.properties.mail.smtp.auth = true;
spring.mail.properties.mail.smtp.starttls.enable = true
spring.mail.properties.mail.transport.protocol = smtp
spring.mail.properties.mail.smtp.timeout = 5000

Java code:

@Service
public class EmailService{

 private JavaMailSender emailSender;

 public EmailService(JavaMailSender emailSender){
   this.emailSender = emailSender;
 }
 
 @Override
 public void sendEmail(MailModel mailModel) {
     MimeMessage message = emailSender.createMimeMessage();
     try{
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(message,true);
       
        Template template = emailConfig.getTemplate(&quot;email4.ftl&quot;);
        String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, mailModel.getModel());
        mimeMessageHelper.setTo(mailModel.getTo());
        mimeMessageHelper.setText(html, true);
        mimeMessageHelper.setSubject(mailModel.getSubject());
        mimeMessageHelper.setFrom(mailModel.getFrom());

        emailSender.send(mimeMessageHelper.getMimeMessage());
    }catch(Exception e){
        log.error(&quot;exception occurred {}, e.getCause());
    }
 }
}

We tried to debug the code with inetaddress, getting error for that aswell

InetAddress address = null;
try{
 address = InetAddress.getByName(hostname);
} catch(UnknownHostException e){
   log.error(&quot;error occurred while trying to get ipaddress : {}, hostname);
   throw new RuntimeException(e);
}

error stacktrace:

12:45:48 (&quot;timestamp&quot;:&quot;87-03-2023 GHT 07:16:35.225&quot;,&quot;level&quot;:&quot;ERROR&quot;, &quot;thread&quot;:&quot;http-nio-8881-exec-
7&quot;,&quot;logger&quot;:&quot;com.emailer.service.FreeMarkerEMailSevice&quot;, &quot;message&quot;:&quot;error occurred while trying to get ipaddress &lt;company smtp server&gt; text&quot;:&quot;default&quot;)
12:46:48 {&quot;timestamp&quot;:&quot;07-03-2023 GT 07:16:35.226&quot;,&quot;level&quot;:&quot;ERROR&quot;, &quot;thread&quot;:&quot;http-nio-8881-exec-
7&quot;,&quot;logger&quot;:&quot;org.apache.catalina.core.ContainerBase. [Tomcat].[localhost].[/].[dispatcherServlet]&quot;, &quot;message&quot;:&quot;Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: java.lang.RuntimeException: java.net.UnknownHostException &lt;company smtp server&gt;: Try again) with root cause&quot;, &quot;context&quot;:&quot;default&quot;, &quot;exception&quot;:&quot;java.net.UnknownHostException: &lt;company smtp server&gt;: Try again\n\ java.base/java.net.InetAddressImpl.lookupAllHostAddr(Native Method)\n\tat
java.base/java.net.InetAddress.PlatformameService.lookupAllHostAddr(InetAddress.java:932)\n\tat
java.base/java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1517)\n\tat
java.base/java.net.InetAdd eServiceAddresses.get(InetAddress.java:851)\n\tat
java.base/java.net.InetAddress.getAllByName0(InetAddress.java:1587)\n\tat java.base/java.net.InetAddress.getAllByName(InetAddress.java:1366)\n\t
java.base/java.net.InetAddress.getAllByName(InetAddress.java:1300)\n\tat java.base/java.net.InetAddress.getByName(InetAddress.java:1250)\n\tat

we tried to compile it into a jar file and run it in one of the aws vm with hostname and java 17, able to trigger an email successfully.

答案1

得分: 1

以下是您要翻译的代码部分:

EmailConfig:

@Configuration
public class EmailConfig {

    @Value("${spring.mail.username}")
    private String noReplyEmailId;

    @Value("${spring.mail.password}")
    private String noReplyEmailPassword;

    @Bean
    public Session getSession() {
        Properties props = new Properties();
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.required", "true");
        props.put("mail.smtp.ssl.protocols", "TLSv1.2");
        return Session.getInstance(props, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(noReplyEmailId, noReplyEmailPassword);
            }
        });
    }
}

EmailService:

@Autowired
Session session;

public void sendVerifyEmail() throws MessagingException {
    try {
    MimeMessage message = new MimeMessage(session);
    MimeMessageHelper helper = new MimeMessageHelper(message, 
    MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED, 
    StandardCharsets.UTF_8.name());
    helper.setFrom();
    helper.setTo();
    helper.setSubject();
    helper.setText();
    Transport.send(message);
    }catch (Exception e) {
         System.out.println("Problem occurred while sending email" + e);
       }
}
英文:

You can use Session class and use Transport.send(). Below is my code for reference :

EmailConfig :

@Configuration
public class EmailConfig {

    @Value(&quot;${spring.mail.username}&quot;)
    private String noReplyEmailId;

    @Value(&quot;${spring.mail.password}&quot;)
    private String noReplyEmailPassword;

    @Bean
    public Session getSession() {
        Properties props = new Properties();
        props.put(&quot;mail.smtp.starttls.enable&quot;, &quot;true&quot;);
        props.put(&quot;mail.smtp.host&quot;, &quot;smtp.gmail.com&quot;);
        props.put(&quot;mail.smtp.port&quot;, &quot;587&quot;);
        props.put(&quot;mail.smtp.auth&quot;, &quot;true&quot;);
        props.put(&quot;mail.smtp.starttls.required&quot;, &quot;true&quot;);
        props.put(&quot;mail.smtp.ssl.protocols&quot;, &quot;TLSv1.2&quot;);
        return Session.getInstance(props, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(noReplyEmailId, noReplyEmailPassword);
            }
        });
    }
}

EmailService :

@Autowired
Session session;


public void sendVerifyEmail() throws MessagingException {
    try {
    MimeMessage message = new MimeMessage(session);
    MimeMessageHelper helper = new MimeMessageHelper(message, 
    MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED, 
    StandardCharsets.UTF_8.name());
    helper.setFrom();
    helper.setTo();
    helper.setSubject();
    helper.setText();
    Transport.send(message);
    }catch (Exception e) {
         System.out.println(&quot;Problem occurred while sending email&quot; + e);
       }
    }

huangapple
  • 本文由 发表于 2023年7月6日 13:07:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76625668.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定