开发者

Sending emails over SMTP with TSL

The code posted below works fine for me to send an email over an STMP with SSL. Now the SMTP changed to TSL and i dont manage to send email with it. I tried several things like adding

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

but it was no use.

The error code says:

"javax.mail.MessagingException: Could not connect to SMTP host: exch.studi.fhws.de, port: 587; nested exception is: javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?"

Any ideas?

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);
    }
}
}


The error message says you're connecting to port 587 - this is an SSL-enabled email port, which means the connection has to be SSL from the get-go. Your code is connecting via plaintext (e.g. plain port 25) and THEN attempting to start TLS. This won't work, as port 587 expects an SSL exchange immediately, not a "EHLO ... / STARTTLS" plaintext command set.


Maybe this answer, talking about Exchange servers with SMTP ports disabled, is useful: https://stackoverflow.com/a/12631772/187148

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜