javax.mail.MessagingException: Could not connect to SMTP host: smtp.xx.com, port: 465;

本文介绍了一种使用javax.mail通过SMTP发送邮件的方法,并解决了在Eclipse环境下遇到的连接异常问题。该问题源于JDK 1.8的安全级别设置,通过调整配置成功解决了问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用javax.mail,通过SMTP来发送邮件,代码如下:

	@Override
	public void validateMail(String to) throws Exception{
		//创建Properties,并设置主机和认证
		Properties props = new Properties();
		props.setProperty("mail.host", "smtp.qq.com");
		props.setProperty("mail.smtp.auth", "true");
		
		//开启SSL加密
		MailSSLSocketFactory sf = new MailSSLSocketFactory();
		sf.setTrustAllHosts(true);
		props.put("mail.smtp.ssl.enable", "true");
		props.put("mail.smtp.ssl.socketFactory", sf);

		//创建Authenticator内部类,重写getPasswordAuthentication()方法
		Authenticator auth = new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication("userName", "password");
			}
		};
		//获取Session
		Session session = Session.getInstance(props, auth);
		
		//创建MimeMessage
		MimeMessage msg = new MimeMessage(session);
		msg.setFrom(new InternetAddress("---------@qq.com"));
		msg.setRecipients(RecipientType.TO, to);
		
		msg.setSubject("来自的一封邮件");
		msg.setContent("这是一封垃圾邮件", "text/html;charset=utf-8");
		
		//发送
		Transport.send(msg);
	}
测试时抛出异常:

javax.mail.MessagingException: Could not connect to SMTP host: smtp.qq.com, port: 465;

解决办法:

我的环境是eclipse,过去在myeclipse中这段代码是没有错的。找出以前写的项目,测试了下,依旧是能正确运行的。

在网上寻找了一些相关信息:http://blog.csdn.net/levy_cui/article/details/51143104

这篇博客的评论里说jdk1.8的security级别问题导致的,按照他的说法实验了一下,问题成功解决。

附上下载地址:百度网盘