banner image
Sedang Dalam Perbaikan

Send emails via localhost with Spring Boot (Java)



Hi guys! Have you ever tried Java in web development? Is it unfamiliar? May be..For me also, it was awkward to hear at first time. When I started learning Spring Boot, I understood it's very easy with Spring Boot to do such a work. This is an elegant framework to build web applications using Java, very easily.

Let's start!


Step 1 - Create a Spring Boot project

First we need to create a fresh project in Spring Boot..But how to do it? Do you have an IDE like IntelliJ IDEA? I recommend to use it.. Using IntelliJ IDEA, we can easily create a project using a plugin. Just read first part of this article I wrote before, to get an idea.
https://salitha94.blogspot.com/2018/11/create-rest-api-using-java-spring-boot.html

If you are not having a licensed version of IntelliJ IDEA, just go for Eclipse. It's totally free. However, I'm not going to explain the steps for creating the project here..You can find it. Let me to focus on the main goal of my article. The initial project structure is shown here..


Note: Here you can see a file called ubuntu.jpg..That file is placed by me for a future purpose of this article.

Let me explain the folder structure...

In Spring Boot we can implement a MVC like architecture for this project. Not really full MVC architecture. But full MVC architecture is also allowed in Spring Boot. Simply in a REST API created with Java, Controller is the connector of end points of the actions. Its logic should be simple. To reach this target, we use a different approach rather than coding the logic in controller directly. We create a Service..It is the interface that holds the functionalities of our task..Since it's and interface, methods have no bodies. So we have to implement the method bodies in a separate place. Its called ServiceImpl. Then we inject a instance of this service into the controller class using an annotation available in Spring Boot called @Aurowired..

We are going to try this with Gmail! Some configurations may be changed for another mail server..
First you need to allow less secure apps in your receiving gmail account.. It's available under security page.

Step 2 - Add Maven dependency

Before implementation, we have to do a very important thing! The Maven dependency to use Java mail functionalities, is needed to be included in our pom.xml file. Open it and place this as a dependency.
<dependency>
     <groupId>javax.mail</groupId>
     <artifactId>mail</artifactId>
     <version>1.4.7</version>
</dependency>
Import changes to add it to the project.

Step 3 -  Implement a service to add logic

This is the place we place our logic.. So I created a file called MailService in controller folder. It's and interface..Just add the method definition into it.I create a java method called sendMail.

MailService.java
package com.spring.mail.service;

import org.springframework.web.bind.annotation.RequestBody;

public interface MailService {

    Object sendMail(@RequestBody String to);
}
Now I need and implementation for this. I created another folder in service folder called impl. Then I placed MailServiceImpl file. Name must be Service Name + Impl.. It's a must!
I'm going to play with the maven dependency we added before.. It provides us a bunch of classes to use in the project. Here, I need to just override the method in interface.

MailServiceImpl.java

package com.spring.mail.service.impl;

import com.spring.mail.service.MailService;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

@Service
public class MailServiceImpl implements MailService {

    @Override
    public Object sendMail() {

        // Set required configs
        String from = "from_mail@gmail.com";
        String to = "to_mail@gmail.com";
        String host = "smtp.gmail.com";
        String port = "587";
        String user = "from_mail@gmail.com";
        String password = "from_mail_password";

        // Set system properties
        Properties properties = System.getProperties();
        properties.put("mail.smtp.auth", "true");
        properties.setProperty("mail.smtp.host", host);
        properties.setProperty("mail.smtp.port", port);
        properties.setProperty("mail.smtp.user", user);
        properties.setProperty("mail.smtp.password", password);
        properties.setProperty("mail.smtp.starttls.enable", "true");

        // Get the default Session object.
        Session session = Session.getDefaultInstance(properties);

        try {
            // Create a default MimeMessage object.
            MimeMessage message = new MimeMessage(session);
            // Set from email address
            message.setFrom(new InternetAddress(from, "TechPool"));
            // Set the recipient email address
            message.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(to));
            // Set email subject
            message.setSubject("Mail Subject");
            // Set email body
            message.setText("This is message body");
            // Set configs for sending email
            Transport transport = session.getTransport("smtp");
            transport.connect(host, from, password);
            // Send email
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
            System.out.println("done");
            return "Email Sent! Check Inbox!";
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (javax.mail.MessagingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
This is a simple message sending script.. Later I will show you how to send attachments also..

Step 4 - Implement a controller

Now we have to connect the controller to the service. We use Autowired annotation for it. Then we define a mapping for this API end point. We use POST method. Later we can extend this to get receiver's email via a form body.

MailController.java

package com.spring.mail.controller;

import com.spring.mail.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RequestMapping(value = "/")
@RestController
@CrossOrigin
public class MailController {

@Autowired
MailService mailService;

    @RequestMapping(value = "/mail", method = RequestMethod.POST)
    public Object sendEmailMessage() {
        return mailService.sendMail(to);
    }
}
We are ready to use our application. Just run your project. It will be started on port 8080 by default. Your end point for sending email is http://localhost:8080/mail.
Open Postman and try to get the result like this.


This is the email I received..


Additional Implementations...


1. Send attachments with email

I showed you the way to send a simple message. But is you want to send an attachment with this email? How to change this code? Just look at the below code.. Here I use that ubuntu.jpg file as an attachment.

package com.spring.mail.service.impl;

import com.spring.mail.service.MailService;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

@Service
public class MailServiceImpl implements MailService {

    @Override
    public Object sendMail() {

        // Set required configs
        String from = "from_mail@gmail.com";
        String to = "to_mail@gmail.com";
        String host = "smtp.gmail.com";
        String port = "587";
        String user = "from_mail@gmail.com";
        String password = "from_mail_password";

        // Set system properties
        Properties properties = System.getProperties();
        properties.put("mail.smtp.auth", "true");
        properties.setProperty("mail.smtp.host", host);
        properties.setProperty("mail.smtp.port", port);
        properties.setProperty("mail.smtp.user", user);
        properties.setProperty("mail.smtp.password", password);
        properties.setProperty("mail.smtp.starttls.enable", "true");

        // Get the default Session object.
        Session session = Session.getDefaultInstance(properties);

        try {
            // Create a default MimeMessage object.
            MimeMessage message = new MimeMessage(session);
            // Set from email address
            message.setFrom(new InternetAddress(from, "TechPool"));
            // Set the recipient email address
            message.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(to));
            // Set email subject
            message.setSubject("Mail Subject");
            // Initiate body of email address
            BodyPart messageBodyPart = new MimeBodyPart();
            // Set email body
            messageBodyPart.setText("This is message body");
            // Initiate class to send media
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);
            // Set path for attachment
            String filename = "ubuntu.jpg";
            // Bind the attachment
            DataSource source = new FileDataSource(filename);
            messageBodyPart.setDataHandler(new DataHandler(source));
            // Set file name into email
            messageBodyPart.setFileName(filename);
            multipart.addBodyPart(messageBodyPart);
            message.setContent(multipart);
            // Set configs for sending email
            Transport transport = session.getTransport("smtp");
            transport.connect(host, from, password);
            // Send email
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
            System.out.println("done");
            return "Email Sent! Check Inbox!";
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (javax.mail.MessagingException e) {
            e.printStackTrace();
        }
        return null;
    }
}


2. Send email to multiple recipients

If you want to send an email message to multiple recipients at once, you can use this way. Here, we use an array list of internetAddresses.
package com.spring.mail.service.impl;

import com.spring.mail.service.MailService;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Properties;

@Service
public class MailServiceImpl implements MailService {

    @Override
    public Object sendMail() {
 
        // Set required configs
        String from = "from_mail@gmail.com";
        String host = "smtp.gmail.com";
        String port = "587";
        String user = "from_mail@gmail.com";
        String password = "from_mail_password";

        // Set system properties
        Properties properties = System.getProperties();
        properties.put("mail.smtp.auth", "true");
        properties.setProperty("mail.smtp.host", host);
        properties.setProperty("mail.smtp.port", port);
        properties.setProperty("mail.smtp.user", user);
        properties.setProperty("mail.smtp.password", password);
        properties.setProperty("mail.smtp.starttls.enable", "true");

        // Get the default Session object.
        Session session = Session.getDefaultInstance(properties);

        try {
            // Create a default MimeMessage object.
            MimeMessage message = new MimeMessage(session);
            // Set from email address
            message.setFrom(new InternetAddress(from, "TechPool"));
            // Set the recipient email address
            ArrayList<String> recipients = new ArrayList<>();
            recipients.add("poolsaliya@gmail.com");
            recipients.add("salithachathuranga94@gmail.com");
            InternetAddress[] addresses = new InternetAddress[recipients.size()];
            for (int i = 0; i < recipients.size(); i++) {
                addresses[i] = new InternetAddress(recipients.get(i));
            }
            message.addRecipients(MimeMessage.RecipientType.TO, addresses);
            // Set email subject
            message.setSubject("Mail Subject");
            // Initiate body of email address
            BodyPart messageBodyPart = new MimeBodyPart();
            // Set email body
            messageBodyPart.setText("This is message body");
            // Initiate class to send media
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);
            // Set path for attachment
            String filename = "ubuntu.jpg";
            // Bind the attachment
            DataSource source = new FileDataSource(filename);
            messageBodyPart.setDataHandler(new DataHandler(source));
            // Set file name into email
            messageBodyPart.setFileName(filename);
            multipart.addBodyPart(messageBodyPart);
            message.setContent(multipart);
            // Set configs for sending email
            Transport transport = session.getTransport("smtp");
            transport.connect(host, from, password);
            // Send email
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
            System.out.println("done");
            return "Email Sent! Check Inbox!";
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (javax.mail.MessagingException e) {
            e.printStackTrace();
        }
        return null;
    }
}


3. Send HTML message

if you want to send a HTML section via an email, you can use this way.

package com.spring.mail.service.impl;

import com.spring.mail.service.MailService;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Properties;

@Service
public class MailServiceImpl implements MailService {

    @Override
    public Object sendMail() {

        // Set required configs
        String from = "from_mail@gmail.com";
        String to = "to_mail@gmail.com";
        String host = "smtp.gmail.com";
        String port = "587";
        String user = "from_mail@gmail.com";
        String password = "from_mail_password";

        // Set system properties
        Properties properties = System.getProperties();
        properties.put("mail.smtp.auth", "true");
        properties.setProperty("mail.smtp.host", host);
        properties.setProperty("mail.smtp.port", port);
        properties.setProperty("mail.smtp.user", user);
        properties.setProperty("mail.smtp.password", password);
        properties.setProperty("mail.smtp.starttls.enable", "true");

        // Get the default Session object.
        Session session = Session.getDefaultInstance(properties);

        try {
            // Create a default MimeMessage object.
            MimeMessage message = new MimeMessage(session);
            // Set from email address
            message.setFrom(new InternetAddress(from, "TechPool"));
            // Set the recipient email address
            message.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(to));
            // Set email subject
            message.setSubject("Mail Subject");
            // Set email body
            message.setContent("<h1>hello</h1>","text/html");
            // Set configs for sending email
            Transport transport = session.getTransport("smtp");
            transport.connect(host, from, password);
            // Send email
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
            System.out.println("done");
            return "Email Sent! Check Inbox!";
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (javax.mail.MessagingException e) {
            e.printStackTrace();
        }
        return null;
    }
}

4. CC or BCC a message to a recipient

If you want to send a Carbon Copy or Blind Carbon Copy of your email message, you can try this way. You have to add a recipient with RecipientType.CC and RecipientType.BCC. Add these two lines into the code.

String cc = "cc_mail@gmail.com";
message.addRecipient(MimeMessage.RecipientType.CC, new InternetAddress(cc));



This is the end of my article.. I tried my best to give you the idea of sending emails via Gmail. So, I hope this will be a help for you! Try this with your own applications and feel free to ask the problems you encountered..

Good Bye!




Send emails via localhost with Spring Boot (Java) Send emails via localhost with Spring Boot (Java) Reviewed by DAL on January 24, 2019 Rating: 5

No comments:

Powered by Blogger.