org.apache.commons.mail.EmailException:将电子邮件发送到以下服务器失败:smtp.gmail.com:465

问题描述 投票:0回答:1

我有一个 Maven 项目,使用 JSF 2.2、Tomcat 7 并使用

Apache Commons
发送电子邮件。

这是我的代码

try {
    // Create the email message
    HtmlEmail email = new HtmlEmail();
    email.setSmtpPort(465); //email.setSslSmtpPort("465");
    email.setSSLOnConnect(true);
    email.setHostName("smtp.gmail.com");
    email.addTo("[email protected]", "test");
    email.setFrom(getEmail(), getName());
    email.setSubject(getSubject());
    email.setHtmlMsg("<html>Test</html>"); // set the html message
    email.setTextMsg(getText());// set the alternative message
    email.send();// send the email
} catch (EmailException e) {
    logger.error("Exception sending email: ", e);
} catch (Exception ex) {
    logger.error("Exception sending email: ", ex);
}

当我尝试在 Tomcat 7 中运行代码时,出现以下异常:

org.apache.commons.mail.EmailException:将电子邮件发送到 以下服务器失败:smtp.gmail.com:465

java email tomcat jakarta-mail
1个回答
0
投票

这是因为 SMTP 中继需要身份验证,您必须使用 gmail 用户/密码登录才能使用中继。

我以前从未使用过通用电子邮件,但经过一番谷歌搜索后,我发现了这个可以通过gmail发送电子邮件。

HtmlEmail email = new HtmlEmail();

String authuser = "user";
String authpwd = "pass";

email.setAuthenticator(new DefaultAuthenticator(authuser, authpwd));

email.setHostName("smtp.gmail.com");

// properties to configure encryption
email.getMailSession().getProperties().put("mail.smtps.auth", "true");
email.getMailSession().getProperties().put("mail.debug", "true");
email.getMailSession().getProperties().put("mail.smtps.port", "587");
email.getMailSession().getProperties().put("mail.smtps.socketFactory.port", "587");
email.getMailSession().getProperties().put("mail.smtps.socketFactory.class",   "javax.net.ssl.SSLSocketFactory");
email.getMailSession().getProperties().put("mail.smtps.socketFactory.fallback", "false");
email.getMailSession().getProperties().put("mail.smtp.starttls.enable", "true");
© www.soinside.com 2019 - 2024. All rights reserved.