通过 Exchange 使用 Javamail 发送电子邮件

Sending Email using Javamail via Exchange

我在使用我公司的交换服务器通过 Javamail 发送电子邮件时遇到了一些问题。我们有一个应用程序可以通过 gmail 服务器发送电子邮件,没有任何问题,但是对于 Google 政策的一些更改,我们希望使用公司服务器来完成这项工作。 我确定会话属性中存在问题,但我找不到使其工作的方法

    Properties props = new Properties();
    props.put("mail.smtp.port", 465);
    props.put("mail.smtp.socketFactory.port", 465);
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");
    props.put("mail.smtp.auth", "true");
    props.put("mail.debug", "true");
    props.put("mail.smtp.host", _server);

    session = Session.getInstance(props, this);
    try {
        transport = session.getTransport("smtp");
        transport.connect("mail.company.com",_user,_pass);
        transport.close();

这是显示日志的错误

javax.mail.MessagingException: Could not connect to SMTP host: mail.company.com, port: 443; nested exception is: avax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

您必须检查您的电子邮件提供商及其 SMTP 设置;服务器、端口和加密方法。

以下代码片段适用于我

        //1) get the session object     
        Properties properties = new Properties();
        properties.put("mail.smtp.auth", "true");
        // You have missed this line.
        properties.put("mail.smtp.starttls.enable", "true");
        // This SMTP server works with me for all Microsoft email providers, like: -
        // Outlook, Hotmail, Live, MSN, Office 365 and Exchange.
        properties.put("mail.smtp.host", "smtp.live.com");
        properties.put("mail.smtp.port", "587");
        properties.put("mail.smtp.user", user);
        properties.put("mail.smtp.pwd", password);

        Session session = Session.getInstance(properties, null);
        session.setDebug(true); // To trace the code implementation.

        Transport transport = session.getTransport("smtp");
        transport.connect("smtp.live.com", 587, user, password);
        transport.close();

而不是

    props.put("mail.smtp.port", 465);
    props.put("mail.smtp.socketFactory.port", 465);
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");
    props.put("mail.smtp.auth", "true");
    props.put("mail.debug", "true");
    props.put("mail.smtp.host", _server);

    session = Session.getInstance(props, this);
    try {
        transport = session.getTransport("smtp");
        transport.connect("mail.company.com",_user,_pass);
        transport.close();

我发现 this website 对获取其他电子邮件提供商的 SMTP 设置信息很有帮助。