Send GMAIL emails from Java and Spring

Carvia Tech | November 02, 2019 | 4 min read | 1 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.
Table of contents
  1. MailSender vs JavaMailSender

  2. GMAIL account setup

  3. GMAIL 2 factor security setup

  4. Sending plain text emails with Spring

  5. Sending multimedia rich text emails with Spring

  6. Sending emails with attachment in Spring

  7. TLS and SMTP configuration

Gradle Configuration

We need to include the mail starter for spring boot project:

build.gradle - Gradle configuration
dependencies {
    compile('org.springframework.boot:spring-boot-starter-mail')
}

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

Allow less secure apps

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.

google app passwords

In the App passwords screen, select app as Mail and device as Custom Device, provide name something as "java mail program"

google generate password

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.

JavaMailSender.java - bean configuration
@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.

MailService.java - Send plain text email
@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:

MailService.java - multimedia support
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.

MailService.java - Attachment 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:
  1. Top 30 Hibernate and Spring Data JPA interview questions
  2. Citibank Java developer interview questions
  3. Top 50 Multi-threading Java Interview Questions for Investment Bank
  4. Cracking core java interviews - question bank
  5. Goldman Sachs Java Interview Questions for Senior Developer
  6. Morgan Stanley Investment Banking Java Interview Questions
  7. Sapient Global Market Java Interview Questions and Coding Exercise



Find more on this topic:
Java Interviews image
Java Interviews

Interview - Product Companies, eCommerce Companies, Investment Banking, Healthcare Industry, Service Companies and Startups.

Last updated 1 week ago


Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info