Spring(非boot)通過ssl傳送郵件
阿新 • • 發佈:2018-11-28
參考: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[]{"收件人[email protected]", "收件人[email protected]"}; 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("[email protected]"); message.setSubject(subject); message.setText(content, true); } }; mailSender.send(preparator);