[JAVA]mail发邮件时提示RSA premaster secret error

使用Java mail发邮件时提示: 

javax.net.ssl.SSLKeyException: RSA premaster secret error

原因:

$JAVA_HOME/jre/lib/ext目录下的四个jar: dnsns.jar,localedata.jar,sunjce_provider.jar,sunpkcs11.jar 未加到classpath中。

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

public class MailDemo{
    public static void main(String[] args){
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        final String SSL_FACTORY="javax.net.ssl.SSLSocketFactory";
        
        String to = "[email protected]";
        String from="[email protected]";
        String host="smtp.139.com";

        Properties props = System.getProperties();
        props.setProperty("mail.smtp.host",host);
        props.setProperty("mail.smtp.socketFactory.class",SSL_FACTORY);
        props.setProperty("mail.smtp.socketFactory.fallback","false");
        props.setProperty("mail.smtp.port","465");
        props.setProperty("mail.smtp.socketFactory.port","465");
        props.put("mail.smtp.ssl.enable",true);
        props.put("mail.smtp.auth",true);
        
        Session session = Session.getDefaultInstance(props,new Authenticator(){
            public PasswordAuthentication getPasswordAuthentication(){
                return new PasswordAuthentication(from, "mypassword"); 
            }
        });
        
        try{
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
            message.setSubject("This is the subject line");
            Multipart multipart = new MimeMultipart();
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText("This is a message body");
            multipart.addBodyPart(messageBodyPart);
            messageBodyPart = new MimeBodyPart();
            String filename = "ArrayDemo.java";
            DataSource dataSource = new FileDataSource(filename);
            messageBodyPart.setDataHandler(new DataHandler(dataSource));
            messageBodyPart.setFileName(filename);
            multipart.addBodyPart(messageBodyPart);
            message.setContent(multipart);

            Transport.send(message);
            System.out.println("Sent message successfully...");
        }
        catch(MessagingException e){
            e.printStackTrace();
        }
       
    }
}

猜你喜欢

转载自my.oschina.net/u/136074/blog/997750