如何在Spring Boot中设置经过身份验证的JavaMailSender

时间:2018-05-09 02:01:58

标签: java spring spring-boot properties javamail

我似乎无法通过Spring Boot的application.properties正确配置Spring的JavaMailSender实现。

以下使用标准JavaMail API的代码可以很好地发送电子邮件:

Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "587");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "587");

Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication("username", "password");
    }
});

try {

    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress("sender@gmail.com"));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipientaddress@gmail.com"));
    message.setSubject("Test Message");
    message.setText("This is a test message.");

    Transport.send(message);
    System.out.println("Sent");
} catch (MessagingException e) {
    throw new RuntimeException(e);
}

我的Spring Boot应用程序application.properties包含以下与电子邮件递送相关的属性:

spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.properties.mail.smtp.auth=true
spring.mail.username=username
spring.mail.password=password
spring.mail.properties.mail.transport.protocol=smtp
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=3000
spring.mail.properties.mail.smtp.writetimeout=5000

Spring Boot应用程序中的以下代码不发送任何电子邮件,但它也没有抛出任何异常:

@Autowired
private JavaMailSender emailSender;

@RequestMapping("/sendEmail")
public ResponseEntity<Void> sendEmail(HttpServletRequest httpRequest) {

    try {

        MimeMessage message = emailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message);
        helper.setFrom("sender@gmail.com");
        helper.setTo("recipientaddress@gmail.com");
        helper.setText("This is a test message.");
        helper.setSubject("Test Message");
        emailSender.send(message);
        System.out.println("Sent");
    }
    catch (MessagingException me) {
        logger.error("Failed to send email: {}", me.getMessage());
    }

    return new ResponseEntity<Void>(null, HttpStatus.OK);
}

1 个答案:

答案 0 :(得分:0)

使用标准JavaMail API时,您使用进行验证

new PasswordAuthentication ("username", "password");

使用Spring Boot时,您没有进行身份验证,有两种选择:

  1. 使用application.properties中的用户和密码进行身份验证,创建与JavaMail API所使用的会话类似的会话
  2. 委托Spring Boot身份验证,从application.properties中删除所有与电子邮件配置相关的设置,并使用服务器上定义的设置,并替换为
  

spring.mail.jndi-name = java:jboss / mail / exampleJboss

sendEmail方法将与JavaMailSender一起使用