dependencies {
compile('org.springframework.boot:spring-boot-starter-mail')
}
Spring Boot with GMAIL SMTP
Upasana | January 07, 2020 | 4 min read | 63 views
In this article we will learn how to send emails from Java and Spring boot applications using GMAIL provider, along with additional concepts like TLS vs SSL, App Passwords in GMAIL, plain-text vs rich multimedia emails.
-
MailSender vs JavaMailSender
-
GMAIL account setup
-
GMAIL 2 factor security setup
-
Sending plain text emails with Spring
-
Sending multimedia rich text emails with Spring
-
Sending emails with attachment in Spring
-
TLS and SMTP configuration
Gradle Configuration
We need to include the mail starter for spring boot project:
spring-boot-starter-mail
will transitively pull in java mail dependencies.
MailSender vs JavaMailSender
MailSender in package org.springframework.mail
is an interface that provides strategy for sending simple emails. For all richer functionality like MIME message or messages with attachments, we shall consider using JavaMailSender (it extends MailSender) in package org.springframework.mail.javamail
.
The production implementation for JavaMailSender is JavaMailSenderImpl. The recommended way of using this interface is the MimeMessagePreparator
mechanism, possibly using a MimeMessageHelper
for populating the message.
TLS vs SSL option
SSL and TLS are cryptographic protocols that provide data encryption and authentication between a server and a client over a network.
SSL was originally developed by Netscape back in 1995, and it had version SSL 1.0, SSL 2.0 and SSL 3.0 But SSL is deprecated now (as of 2015).
TLS is successor to SSL, TLS 1.0 was introduced in 1999 based on SSL 3.0, TLS is currently at v1.2 at the time of writing this article. We shall always prefer to use TLSv1.2 over SSL for security reasons.
Less secure apps in GMAIL
You can enable less secure apps option in GMAIL if you do not want to enable 2 factor authentication. Thiw will allow you to use your gmail password directly in the SMTP configuration for sending emails. But this option is less secure and should be avoided.
So In order to allow us to send email via gmail, you will have to login to your gmail or sender’s gmail account and then visit this link :
When you will visit this link, you will see this
Click on the slider to allow less secure apps. Once, this is ON we will be able to send email via gmail account.
App password setup in GMAIL
The preferred approach for sending emails using GMAIL is to setup App password using GMAIL security options.
Goto https://accounts.google.com and then select Security and then choose Signing in to Google and then select App passwords.
In the App passwords screen, select app as Mail and device as Custom Device, provide name something as "java mail program"
Then click on generate. This will generate app password which should be used instead of real account password in email SMTP authentication.
JavaMailSender Bean
First step is to create a Bean of type JavaMailSender
that is configured with GMAIL smpt properties. We will be using TLS on port 587 for this tutorial.
@Configuration
public class GmailConfig {
@Bean("gmail")
public JavaMailSender gmailMailSender() {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost("smtp.gmail.com");
mailSender.setPort(587);
mailSender.setUsername("foo@gmail.com");
mailSender.setPassword("---app password----");
Properties props = mailSender.getJavaMailProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.debug", "false");
return mailSender;
}
}
Send plain text email
Now we will create a service that will use the previously created JavaMailSender
bean for sending email using GMAIL.
@Service
public class MailService {
private static final Logger logger = LoggerFactory.getLogger(MailService.class);
@Autowired
@Qualifier("gmail")
private JavaMailSender mailSender;
public void sendMail(String from, String subject, String toAddresses, String ccAddresses, String bccAddresses, String body) {
MimeMessagePreparator preparator = mimeMessage -> {
MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
message.setTo(toAddresses.split("[,;]"));
message.setFrom(from, "<From Name>");
message.setSubject(subject);
if (StringUtils.isNotBlank(ccAddresses))
message.setCc(ccAddresses.split("[;,]"));
if (StringUtils.isNotBlank(bccAddresses))
message.setBcc(bccAddresses.split("[;,]"));
message.setText(body, false);
};
mailSender.send(preparator);
logger.info("Email sent successfully To {},{} with Subject {}", toAddresses, ccAddresses, subject);
}
}
Send rich multimedia email
The only change we need to make for multimedia emails is:
message.setText(body, true);
This will use given message body content as html and format the email. You can generate HTML using velocity, freemarker or any other template engine.
Sending attachment with email
MimeMessageHelper
provides addAttachment(…)
method to support file attachments in emails. The following code illustrates how a list of files can be attached to email message using Spring framework support.
List<File> attachments = ArrayList<>();
atatchments.add(...);
//Add more files
attachments.forEach(file -> {
try {
FileSystemResource resource = new FileSystemResource(file);
message.addAttachment(file.getName(), resource);
} catch (MessagingException e) {
throw new RuntimeException("Problem attaching file to email", e);
}
});
That’s all.
Top articles in this category:
- Mandrill emails in Spring Boot Java
- Top 50 Spring Interview Questions
- Hibernate & Spring Data JPA interview questions
- Cracking core java interviews - question bank
- Multi-threading Java Interview Questions for Investment Bank
- Sapient Global Market Java Interview Questions and Coding Exercise
- ION Trading Java Interview Questions