在SpringBoot中使用JavaMailSender

时间:2017-03-10 19:30:11

标签: java spring spring-mvc spring-boot smtp

我使用Spring Initializer,嵌入式Tomcat,Thymeleaf模板引擎和包作为可执行的JAR文件生成了一个Spring Boot Web应用程序。

使用的技术:

Spring Boot 1.4.2.RELEASE,Spring 4.3.4.RELEASE,Thymeleaf 2.1.5.RELEASE,Tomcat Embed 8.5.6,Maven 3,Java 8

我已创建此服务以发送电子邮件

@Service
public class MailClient {

    protected static final Logger looger = LoggerFactory.getLogger(MailClient.class);

    @Autowired
    private JavaMailSender mailSender;

    private MailContentBuilder mailContentBuilder;

    @Autowired
    public MailClient(JavaMailSender mailSender, MailContentBuilder mailContentBuilder) {
        this.mailSender = mailSender;
        this.mailContentBuilder = mailContentBuilder;
    }

    //TODO: in a properties
    public void prepareAndSend(String recipient, String message) {
        MimeMessagePreparator messagePreparator = mimeMessage -> {
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
            messageHelper.setFrom("nunito@calzada.com");
            messageHelper.setTo(recipient);
            messageHelper.setSubject("Sample mail subject");
            String content = mailContentBuilder.build(message);
            messageHelper.setText(content, true);
        };
        try {
            if (looger.isDebugEnabled()) {
                looger.debug("sending email to " + recipient);
            }
            mailSender.send(messagePreparator);
        } catch (MailException e) {
            looger.error(e.getMessage());
        }
    }
}

但是在Init the SpringBootApplication

时我遇到了这个错误
***************************
APPLICATION FAILED TO START
***************************

Description:

Binding to target org.springframework.boot.autoconfigure.mail.MailProperties@1e94ed11 failed:

    Property: spring.mail.defaultEncoding
    Value: UTF-8 
    Reason: Failed to convert property value of type 'java.lang.String' to required type 'java.nio.charset.Charset' for property 'defaultEncoding'; nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [java.nio.charset.Charset]


Action:

Update your application's configuration

这是我的application.properties

spring.mail.host=localhost
spring.mail.port=25 
spring.mail.username= 
spring.mail.password= 
spring.mail.protocol=smtp
spring.mail.defaultEncoding=UTF-8 

1 个答案:

答案 0 :(得分:1)

您不能在与该属性相同的行中添加注释。每个评论都必须以'#'开头。 错误消息显示

Value: 25 # SMTP server port

所以值是字符串 25#SMTP服务器端口'并且无法转换为整数。

将评论移到自己的行中,位于属性上方:

# SMTP server port
spring.mail.port=25