我正在尝试使用Spring Boot发送电子邮件,但得到了:
java.lang.UnsupportedOperationException: Method not yet implemented at javax.mail.internet.MimeMessage.<init>(MimeMessage.java:89) at org.springframework.mail.javamail.SmartMimeMessage.<init>(SmartMimeMessage.java:52) at org.springframework.mail.javamail.JavaMailSenderImpl.createMimeMessage(JavaMailSenderImpl.java:325)
我已经使用了这个Maven条目:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.2.6.RELEASE</version> </parent> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>1.2.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> <version>1.2.6.RELEASE</version> </dependency>
application.properties:
spring.mail.host=smtp.gmail.com spring.mail.port= 25 spring.mail.username= test spring.mail.password= test
和我的代码:
@Autowired private JavaMailSender javaMailSender; private void send() { MimeMessage mail = javaMailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(mail, true); helper.setTo("mymail@mail.co.uk"); helper.setReplyTo("someone@localhost"); helper.setFrom("someone@localhost"); helper.setSubject("Lorem ipsum"); helper.setText("Lorem ipsum dolor sit amet [...]"); } catch (MessagingException e) { e.printStackTrace(); } finally {} javaMailSender.send(mail); //return helper; }
这似乎很简单,但是我不缺少什么!
我的建议是使用it.ozimov:spring-boot-email-core库,该库将所有这些实现隐藏在一个单独的组件后面EmailService-很好,我也在开发该库:)。
EmailService
您的示例将是:
@Autowired public EmailService emailService; public void sendEmail(){ final Email email = DefaultEmail.builder() .from(new InternetAddress("mymail@mail.co.uk")) .replyTo(new InternetAddress("someone@localhost")) .to(Lists.newArrayList(new InternetAddress("someone@localhost"))) .subject("Lorem ipsum") .body("Lorem ipsum dolor sit amet [...]") .encoding(Charset.forName("UTF-8")).build(); emailService.send(email); }
具有以下内容application.properties:
application.properties
spring.mail.host=your.smtp.com spring.mail.port=587 spring.mail.username=test spring.mail.password=test spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.starttls.required=true
它还支持某些模板引擎,例如 Freemarker , Mustache 和 Pebble ,而您可以扩展它以使用更多的模板引擎。此外,它还支持电子邮件调度和优先级排序(例如,密码恢复的高优先级和新闻通讯的低优先级)。
LinkedIn上有一篇文章介绍了如何使用它。这是在这里。