QQ 邮箱开启 POP3/SMTP 服务,获取 QQ 邮箱授权码
导入相关 jar 包依赖
<dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId><version>5.3.8</version></dependency><dependency><groupId>javax.mail</groupId><artifactId>mail</artifactId><version>1.4.7</version></dependency>
发送邮件工具类,只能发送简单文本邮件
packageutils; importorg.springframework.mail.SimpleMailMessage; importorg.springframework.mail.javamail.JavaMailSenderImpl; importjava.util.Properties; publicclassEmailUtils { privatestaticfinalJavaMailSenderImplsender=newJavaMailSenderImpl(); static { //服务器sender.setHost("smtp.qq.com"); //协议sender.setProtocol("smtps"); //端口号sender.setPort(465); //邮箱账号sender.setUsername("*********@qq.com"); //邮箱授权码sender.setPassword("************"); //编码sender.setDefaultEncoding("Utf-8"); Propertiesp=newProperties(); p.setProperty("mail.smtp.ssl.enable", "true"); sender.setJavaMailProperties(p); } /*** 发送邮件** @param subject* @param text* @return*/publicstaticbooleansendEmail(Stringsubject, Stringtext) { try { SimpleMailMessagemessage=newSimpleMailMessage(); //设置邮件标题message.setSubject(subject); //设置邮件正文message.setText(text); //设置邮件发送人message.setFrom("************"); //设置邮件接收人message.setTo("************"); //发送邮件sender.send(message); returntrue; } catch (Exceptione) { returnfalse; } } }
测试类
importorg.junit.Test; importutils.EmailUtils; publicclassMailTest { publicvoidsend() { EmailUtils.sendEmail("test", "test"); } }
发送成功