Is there some example of how MailSender can be configured via java config? All examples that I\'ve seen uses xml to create needed beans:
The code you posted (along with some small improvements to make it more configurable) would be transformed into the following Java config:
@Configuration
public class MailConfig {
@Value("${email.host}")
private String host;
@Value("${email.from}")
private String from;
@Value("${email.subject}")
private String subject;
@Bean
public JavaMailSender javaMailService() {
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
javaMailSender.setHost(host);
return javaMailSender;
}
@Bean
public SimpleMailMessage simpleMailMessage() {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setFrom(from);
simpleMailMessage.setSubject(subject);
return simpleMailMessage;
}
}
You should also be aware of the fact that Spring Boot (which you have not mentioned whether or not you are using) can auto-configure an JavaMailSender
for you. Check out this part of the documentation
@Configuration
public class AppConfig {
@Value("${mail.host}")
private String host;
@Bean
public JavaMailSender emailService() {
JavaMailSender javaMailSender = new JavaMailSenderImpl();
javaMailSender.setHost(host);
return javaMailSender;
}
@Component
public class EmailServiceImpl implements EmailService {
@Autowired
public JavaMailSender emailSender;
public void sendSimpleMessage( String to, String subject, String text) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(text);
emailSender.send(message);
}
}