今天在使用javamail发送邮件到qq邮箱的过程中,遇到了一些问题
刚开始按网上的代码写
// 发送纯文本信息 Properties prop = new Properties(); prop.setProperty("mail.smtp.host", "smtp.qq.com"); // 注意,企业邮箱地址不同 prop.setProperty("mail.transport.protocol", "smtp"); prop.put("mail.smtp.auth", true); // 此处的true不要使用字符串形式的"true", 被坑过..... prop.setProperty("mail.smtp.port", "465"); Session session = Session.getDefaultInstance(prop, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("[email protected]", "xxxxx"); } }); session.setDebug(true); // 打印调试信息 MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("xx"); message.setText("xxx"); Transport.send(message);
上面的代码在运行的时候是连不上qq邮箱的服务器的,因为qq邮箱采用了ssl协议, 所以上面得加上一行
prop.put("mail.smtp.ssl.enable", "true"); // 启用ssl
在jdk8运行时, 会出现如下异常:
javax.mail.MessagingException: Could not connect to SMTP host: smtp.qq.com, port: 465; nested exception is: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure ...... Caused by: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
经过查找,该问题出现是因为jdk8里面的安全机制的问题,具体见 jdk_jce,
要替换的资源下载地址: http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
覆盖之前记得备份jdk里的原文件
javamail maven 地址: http://mvnrepository.com/artifact/javax.mail/mail