Reputation: 429
I currently have a Spring Boot web application and I want to send an email that contains HTML so the email looks more pleasing. Currently I am using SimpleMailMessage.
I would rather not implement a templating engine solely for the purpose of sending a nicely formatted email.
All help is appreciated, thank you.
Upvotes: 0
Views: 2141
Reputation: 8739
If you're in fact using Spring Boot, then you've gotten a really great start for sending messages. Your code can be loosely based on something as simple as:
@Component
public class EmailServiceImpl implements EmailService {
@Autowired
public JavaMailSender emailSender;
@Autowired
public MimeMessage mimeMessage;
public void sendMessage() {
helper.setTo("[email protected]");
helper.setSubject("This is the test message for testing gmail smtp server using spring mail");
helper.setFrom("[email protected]");
mailSender.send(mimeMessage);
}
}
A @Configuration
that looks contains your template:
@Bean
@Scope("prototype")
public MimeMessage templateSimpleMessage(JavaMailSender mailSender) {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
helper.setText("<h3>Hello World!</h3>");
return message;
}
And just configure your mail SMTP destination like so in your application.yml
:
# application.yml
spring:
mail:
default-encoding: UTF-8
host: smtp.gmail.com
username: [email protected]
password: secret
port: 587
properties:
mail:
smtp:
auth: true
starttls:
enable: true
protocol: smtp
test-connection: false
If you want to construct more advanced templates, use Velocity. See example.
Upvotes: 1