Sending email with Spring Boot

Last Update: 14.06.2018. By Jens in Developers Life | Learning | Newsletter

So, let’s start with sending emails first. As with most things in Spring Boot, it is straightforward. The central class in Spring for sending emails is the JavaMailSender. It provides an interface simplifying the whole mail creation process, especially with mime types.

First, we need to add the dependency:

org.springframework.boot spring-boot-starter-mail Adding the dependency alone will not create a JavaMailSender for us, we also must declare an SMTP host at the least minimum.

spring.mail.host=smtp.whatever.com All other parts can be configured with properties under the same _spring.mail_namespace, like spring.mail.username for setting the username for the SMTP host and spring.mail.password for setting the password of that user.

Now, we are ready to go and just auto-wire it in our class like any other Spring bean. We can either create our email by using the SimpleMailMessage for simple emails or go with MimeMessage for complex things like adding multiple attachments, text and HTML views, etc.

I used the later even it is a simple text email. mailSender is my instance of JavaMailSender.

private void notifyJobPosted(final JobPost job) { try { MimeMessage msg = mailSender.createMimeMessage(); msg.setFrom(“hallo@domain.de”); msg.setRecipients(RecipientType.TO, “hallo@domain.de”); msg.setSubject(“New Job posted on Domain”); msg.setText(job.toString()); mailSender.send(msg); } catch (Exception e){ LOGGER.error(“Job created, but could not send email”, e); } } I essentially create a MimeMessage, add the sender and recipient, subject line and add a string representation of a job post as the body text. And in the final step, send it with send method.

Voila! Mail sending done.