无法从服务器通过SMTP发送邮件,但我可以从localhost发送邮件

时间:2017-04-09 20:23:28

标签: java email spring-boot smtp javamail

当我尝试在Java应用程序中通过SMTP发送电子邮件时,我得到以下内容。我正在Windows Server 2012 R2上运行来自胖JAR的Springboot应用程序。

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Sun Apr 09 22:16:57 CEST 2017
There was an unexpected error (type=Internal Server Error, status=500).
Mail server connection failed; nested exception is com.sun.mail.util.MailConnectException: Couldn't connect to host, port: internetsmtp.test.com, 25; timeout -1; nested exception is: java.net.UnknownHostException: internetsmtp.test.com. Failed messages: com.sun.mail.util.MailConnectException: Couldn't connect to host, port: internetsmtp.test.com, 25; timeout -1; nested exception is: java.net.UnknownHostException: internetsmtp.test.com

代码:

public void sendEmail(String from, String replyTo, String to, String subject, String body) {
        final Email email;
        try {
            email = DefaultEmail.builder()
                    .from(new InternetAddress(from))
                    .replyTo(new InternetAddress(replyTo))
                    .to(Lists.newArrayList(new InternetAddress(to)))
                    .subject(subject)
                    .body(body)
                    .encoding("UTF-8").build();
            emailService.send(email);
        } catch (AddressException e) {
            log.error("MailUtil got exception while sending mail = " + e.getMessage());
        }
    }

application.properties:

# Server
server.port=8080

# Mail Config
spring.mail.host: internetsmtp.test.com
spring.mail.port: 25
spring.mail.username: user123
spring.mail.password: test123
spring.mail.properties.mail.smtp.auth: true
spring.mail.properties.mail.smtp.starttls.enable: false
spring.mail.properties.mail.smtp.starttls.required: false
spring.mail.persistence.enabled: false
spring.mail.persistence.redis.embedded: false
spring.mail.persistence.redis.enabled: false
spring.mail.scheduler.priorityLevels=10

我甚至尝试信任证书

keytool -import -file "C:\mail.cer" -keystore "C:\Program Files\Java\jre.1.8.0_121\lib\security\cacerts" -alias mail

我可以从 localhost 完成所有这些操作,没有任何问题。问题可能是我的服务器阻止了与SMTP服务器的连接吗?

2 个答案:

答案 0 :(得分:1)

您的例外明确指出 - java.net.UnknownHostException: internetsmtp.test.com。这意味着(在这种情况下)您的应用程序无法从服务器解析DNS名称。确保您能够从服务器本身ping该域,并且不阻止该服务器的DNS访问(端口53)

答案 1 :(得分:1)

最有可能的是防火墙阻止了直接连接。 JavaMail FAQ有更多tips for debugging connection problems