[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 = "to@163.com";
        String from="from@139.com";
        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();
        }
       
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值