Spring(非boot)通过ssl发送邮件
Posted tomcat and jerry
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring(非boot)通过ssl发送邮件相关的知识,希望对你有一定的参考价值。
参考:https://blog.csdn.net/liguo9860/article/details/6874040
我这里就说一下使用Spring的JavaMailSender如何实现
1. 配置JavaMailSender
@Bean public JavaMailSender javaMailSender(){ JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl(); javaMailSender.setDefaultEncoding("UTF-8"); javaMailSender.setUsername(env.getProperty("email.user")); javaMailSender.setPassword(env.getProperty("email.pwd")); javaMailSender.setHost(env.getProperty("email.host")); Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; // Get a Properties object Properties props = System.getProperties(); props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY); props.setProperty("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.port", "465"); props.setProperty("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.auth", "true"); javaMailSender.setJavaMailProperties(props); return javaMailSender; }
2. 发送邮件
String[] receivers = new String[]{"收件人1@qq.com", "收件人2@qq.com"}; String subject = "测试SSL发送邮件,走465端口"; String content = "<h2>哈哈测试, 原文地址:https://home.cnblogs.com/u/tomcatandjerry/</h2>" MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setTo(receivers); if(data.getBcc() != null){ message.setBcc(data.getBcc()); } message.setFrom("179634696@qq.com"); message.setSubject(subject); message.setText(content, true); } }; mailSender.send(preparator);
以上是关于Spring(非boot)通过ssl发送邮件的主要内容,如果未能解决你的问题,请参考以下文章
spring-boot实战12:Spring Boot中使用JavaMailSender发送邮件
Spring Boot中使用JavaMailSender发送邮件