此代码用的jar文件:mail.jar(1.4.5版本);
如果jdk用的是1.8版本会出现SSL错误:这个问题是jdk导致的,jdk1.8里面有一个jce的包,安全性机制导致的访问https会报错,官网上有替代的jar包,如果替换掉就可以了.
这两个jar包的下载地址:http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
下载之后,把这个压缩文件解压,得到两个jar包去覆盖jdk安装目录下的jre\lib\security\下相同的jar包就能解决java8的邮件发送问题。
public static void main(String[] args) throws Exception {
Properties prop = new Properties();
//协议
prop.setProperty("mail.transport.protocol", "smtp");
//服务器
prop.setProperty("mail.smtp.host", "smtp.exmail.qq.com");
//端口
prop.setProperty("mail.smtp.port", "465");
//使用smtp身份验证
prop.setProperty("mail.smtp.auth", "true");
//使用SSL,企业邮箱必需!
//开启安全协议
MailSSLSocketFactory sf = null;
try {
sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
} catch (GeneralSecurityException e1) {
e1.printStackTrace();
}
prop.put("mail.smtp.ssl.enable", "true");
prop.put("mail.smtp.ssl.socketFactory", sf);
//
//获取Session对象
Session s = Session.getDefaultInstance(prop,new Authenticator() {
//此访求返回用户和密码的对象
@Override
protected PasswordAuthentication getPasswordAuthentication() {
PasswordAuthentication pa = new PasswordAuthentication("[email protected]", "Ok1234");
return pa;
}
});
//设置session的调试模式,发布时取消
s.setDebug(true);
MimeMessage mimeMessage = new MimeMessage(s);
try {
mimeMessage.setFrom(new InternetAddress("[email protected]","[email protected]"));
mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
//设置主题
mimeMessage.setSubject("账户密码重置");
mimeMessage.setSentDate(new Date());
//设置内容
mimeMessage.setText("您使用了密码重置功能");
mimeMessage.saveChanges();
//发送
Transport.send(mimeMessage);
} catch (MessagingException e) {
e.printStackTrace();
} }
05-11 17:48