Send Email in Spring Boot Application

Ashutosh Kumar
2 min readJun 1, 2020
Send Email in Spring Boot

While working with Spring Boot application, a developer or a team will always need util to send an email at different points of the code flow. This email might be triggered for some notification, alarms, exception-alerts or anything; all depends on the system design.

Below is the same code which you can directly include in your code base to implement the email functionality.

EmailUtil.java

package com.xyz.ashutosh.utils;

import java.io.IOException;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

@Service
public class EmailUtil {

private static final Logger LOG = LoggerFactory.getLogger(EmailUtil.class);
@Autowired
private Environment environment;

@Value(“${server.name}”)
String serverName;

private static Properties parseEmailProperties() throws IOException {

Properties props = new Properties();
props.load(ClassLoader.getSystemClassLoader().getResourceAsStream(Constants.SMTP_PROPERTIES_FILE));
return props;
}

private Session getSession() throws IOException {

Properties props = setProperties();
// Properties props = parseEmailProperties();
Authenticator authenticator = new Authenticator() {

protected javax.mail.PasswordAuthentication getPasswordAuthentication() {

return new javax.mail.PasswordAuthentication(props.getProperty(Constants.SMTP_USERNAME),
props.getProperty(Constants.SMTP_PASSWORD));
}
};
return Session.getInstance(props, authenticator);
}

public void sendEmail(String toAddress, String replyTo, String subject, String body) {

try {
Session session = getSession();
MimeMessage message = new MimeMessage(session);
message.setRecipients(RecipientType.TO, InternetAddress.parse(toAddress, false));
message.setReplyTo(InternetAddress.parse(replyTo));
message.setSubject(serverName + “ “ + subject);
message.setText(body);
Transport.send(message);
LOG.info(“Mail Successfully sent. To: {}, Subject: {}”, toAddress, subject);
} catch (IOException | MessagingException e) {
LOG.error(“Failed to send an email and exception is: “, e);
}
}

public void sendHtmlEmail(String toAddress, String replyTo, String subject, String body) {

try {
Session session = getSession();
MimeMessage message = new MimeMessage(session);
message.setRecipients(RecipientType.TO, InternetAddress.parse(toAddress, false));
message.setReplyTo(InternetAddress.parse(replyTo));
message.setSubject(serverName + “ “ + subject);
message.setContent(body, “text/html”);
Transport.send(message);
LOG.info(“Mail Successfully sent. To: {}, Subject: {}”, toAddress, subject);
} catch (IOException | MessagingException e) {
LOG.error(“Failed to send an email and exception is: “, e);
}
}

private Properties setProperties() {

Properties props = new Properties();
props.put(“mail.smtp.host”, environment.getProperty(“mail.smtp.host”));
props.put(“mail.smtp.port”, environment.getProperty(“mail.smtp.port”));
props.put(“mail.smtp.auth”, environment.getProperty(“mail.smtp.auth”));
props.put(“mail.smtp.starttls.enable”, environment.getProperty(“mail.smtp.starttls.enable”));
props.put(“mail.username”, environment.getProperty(“mail.username”));
props.put(“mail.password”, environment.getProperty(“mail.password”));
return props;
}
}

Application.properties

mail.smtp.host=smtp.gmail.com
mail.smtp.port=587
mail.smtp.auth=true
mail.smtp.starttls.enable=true
mail.username=abc@xyz.com
mail.password=XXXYYYXXX

Constants.java

public static final String SMTP_PROPERTIES_FILE = “smtp.properties”;
public static final String SMTP_USERNAME = “mail.username”;
public static final String SMTP_PASSWORD = “mail.password”;

--

--

Ashutosh Kumar

Backend Engineering | BIT Mesra | Building Microservices and Scalable Apps | Mentor