使用TLS通过SMTP发送电子邮件

问题描述 投票:2回答:2

下面发布的代码适用于我通过SMTP发送带有SSL的电子邮件。知道对TLS的SMTP更改,我没有设法用它发送电子邮件。我尝试了几件事,比如添加

props.put("mail.smtp.starttls.enable","true");

但这没用。

错误代码说:

“javax.mail.MessagingException:无法连接到SMTP主机:exch.studi.fhws.de,port:587;嵌套异常是:javax.net.ssl.SSLException:无法识别的SSL消息,明文连接?”

有任何想法吗?

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class SendMail
{
String d_email = "...",
password = "...",
host = "...",
port = "25",
mailTo = "...",
mailSubject = "test",
mailText = "test";

public SendMail()
{
    Properties props = new Properties();
    props.put("mail.smtp.user", d_email);
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);
    props.put("mail.smtp.starttls.enable","true");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.socketFactory.port", port);
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");

    SecurityManager security = System.getSecurityManager();

    try
    {
        Authenticator auth = new SMTPAuthenticator();
        Session session = Session.getInstance(props, auth);

        MimeMessage msg = new MimeMessage(session);
        msg.setText(mailText);
        msg.setSubject(mailSubject);
        msg.setFrom(new InternetAddress(d_email));
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
        Transport.send(msg);
    }
    catch (Exception mex)
    {
        mex.printStackTrace();
    }
}

public static void main(String[] args)
{
    TextClass tc = new TextClass();
}

private class SMTPAuthenticator extends javax.mail.Authenticator
{
    public PasswordAuthentication getPasswordAuthentication()
    {
        return new PasswordAuthentication(d_email, password);
    }
}
}
java email smtp javamail ssl
2个回答
0
投票

错误消息显示您正在连接到端口587 - 这是一个启用SSL的电子邮件端口,这意味着连接必须从一开始就是SSL。您的代码通过纯文本(例如普通端口25)连接,然后尝试启动TLS。这不起作用,因为端口587需要立即进行SSL交换,而不是“EHLO ... / STARTTLS”明文命令集。


0
投票

也许这个答案,谈论禁用SMTP端口的Exchange服务器是有用的:https://stackoverflow.com/a/12631772/187148

© www.soinside.com 2019 - 2024. All rights reserved.