返回> 网站首页
基于JavaMail的邮件发送及问题
yoours2022-09-06 20:51:02
简介一边听听音乐,一边写写文章。
一、发送源代码
public static void SendMail(Properties properties, String subject, String content)
{
try {
Properties mailProperties = new Properties();
// 解决ssl发送邮件
mailProperties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
mailProperties.put("mail.smtp.socketFactory.port", String.valueOf(properties.getProperty("mail.port")));
mailProperties.put("mail.smtp.port", String.valueOf(properties.getProperty("mail.port")));
mailProperties.put("mail.transport.protocol", "smtp");
mailProperties.put("mail.smtp.auth", "true");
// 设置SSL
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
mailProperties.put("mail.smtp.ssl.socketFactory", sf);
mailProperties.put("mail.smtp.ssl.enable", "true");
mailProperties.put("mail.smtp.socketFactory.fallback", "true");
Session session = Session.getDefaultInstance(mailProperties, null);
session.setDebug(true);
MimeMultipart mp = new MimeMultipart();
MimeMessage mimeMessage = new MimeMessage(session);
// 设置发信人
mimeMessage.setFrom(new InternetAddress(String.valueOf(properties.getProperty("mail.sender"))));
// 设置接收人
mimeMessage.setRecipients(Message.RecipientType.TO, String.valueOf(properties.getProperty("mail.receiver")));
// 设置主题
mimeMessage.setSubject(subject);
// 设置正文
BodyPart bp = new MimeBodyPart();
bp.setContent(content, "text/html;charset=utf-8");
mp.addBodyPart(bp);
mimeMessage.setContent(mp);
mimeMessage.saveChanges();
// 发送邮件
Transport transport = session.getTransport("smtp");
transport.connect(String.valueOf(properties.getProperty("mail.host")), String.valueOf(properties.getProperty("mail.username")), String.valueOf(properties.getProperty("mail.password")));
transport.sendMessage(mimeMessage, mimeMessage.getRecipients(Message.RecipientType.TO));
transport.close();
} catch (Exception e) {
e.printStackTrace();
}
}
二、问题: java.lang.ClassNotFoundException: com.sun.mail.util.MailLogger
原本pom依赖
<dependency>
<groupId >javax.mail </groupId >
<artifactId >javax.mail- api</ artifactId>
<version >1.6.0 </version >
</dependency>
MailLogger --是JavaMail的一部分,包含在Java EE环境里面,但是不包含在Java SE环境里面,出现这个错误很大的原因是在SE环境里面测试邮件的发送;
javax.mail-api只适合编译,但是如果你实在要运行代码,必须完全实现JavaMail
修改pom依赖
<dependency >
<groupId >javax.mail </groupId >
<artifactId >mail </artifactId >
<version >1.4.7 </version >
</dependency >
三、问题:DEBUG SMTP: trying to connect to host "smtp.exmail.qq.com", port 465, isSSL false
// 设置SSL
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
mailProperties.put("mail.smtp.ssl.socketFactory", sf);
mailProperties.put("mail.smtp.ssl.enable", "true");
mailProperties.put("mail.smtp.socketFactory.fallback", "true");
四、问题: Could not connect to SMTPhost: smtp.qq.com, port:465
修改java运行环境
本地环境的jdk的配置中禁止了这个SLLv3协议,所以本地发送邮件才会一直报错。
解决方案是打开自己安装的jdk目录,找到配置的文件:java.security,将以上内容删除即可。