DEV Community

Mohammed Riyas
Mohammed Riyas

Posted on

Send email using Spring boot Application

Hey amigos in this blog we gonna create an simple email sending springBoot Application.in this application i concentrated more in logical part. So i haven't give importance to design. My aim is to make as more simple and easy to understand.

To send email using spring application first of all you need to make right sure that enable less Secure apps in G-mail. After that then only we can send email from our application. I drop a link for how to enable less secure app please follow up.

https://youtu.be/Ee7PDsbfOUI

lets start with HTML part...

<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <form action="add">
            <input type="text" name="username" placeholder="to whom you gonna send name"/>
            <input type="email" name="email" placeholder="email"/>
        <button type="submit">submit</button>
        </form>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Nothing much complicated. iam just accepting the user name and email send it back to backend.


package com.mail2.mail2.controller;

import com.mail2.mail2.dot.mailRequest;
import com.mail2.mail2.dot.mailresponse;
import com.mail2.mail2.service.mailService;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class controller {
    @RequestMapping("/")
    public String aa()
    {
        return "createUser";
    }
    @RequestMapping("/add")
    public String sp(@RequestParam("username")String name,@RequestParam("email")String email)
    {
       mailresponse mr= sendEmail(email);
        return "success";
    }
    @Autowired 
    private mailService service;
    public mailresponse sendEmail(String request) {
          Map<String, Object> model = new HashMap<>();
        model.put("Name", "riyas");
        model.put("location", "Bangalore,India");
        return service.sendEmail(request, model);
    }
}

Enter fullscreen mode Exit fullscreen mode

create a Mail Request and Mail Response class

package com.mail2.mail2.dot;

public class mailRequest {
      private String name;
    private String to;
    private String from;
    private String subject;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getTo() {
        return to;
    }

    public void setTo(String to) {
        this.to = to;
    }

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

}

Enter fullscreen mode Exit fullscreen mode
package com.mail2.mail2.dot;

public class mailresponse {
        private String message;
    private boolean status;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public boolean isStatus() {
        return status;
    }

    public void setStatus(boolean status) {
        this.status = status;
    }

}

Enter fullscreen mode Exit fullscreen mode

let me explain how the backend code work. first in controller class we accepting the username and email String.then sending email String to sendEmail method. Then creating Map object and send it to sendEmail method in MailService class.


package com.mail2.mail2.service;

import com.mail2.mail2.dot.mailRequest;
import com.mail2.mail2.dot.mailresponse;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

/**
 *
 * @author ELCOT
 */
@Service
public class mailService {
    @Autowired
    JavaMailSender sender;
    @Autowired
    Configuration config;
    public mailresponse sendEmail(String request, Map<String, Object> model) {
        mailresponse response = new mailresponse();
        MimeMessage message = sender.createMimeMessage();
        try {
            // set mediaType
            MimeMessageHelper helper = new MimeMessageHelper(message, MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,
                    StandardCharsets.UTF_8.name());
            // add attachment

            Template t = config.getTemplate("email-template.ftl");
            String html = FreeMarkerTemplateUtils.processTemplateIntoString(t, model);

            helper.setTo(request);
            helper.setText(html, true);
            helper.setSubject("created_successfully");
            helper.setFrom("muhammedriyas6262@gmail.com");
            sender.send(message);

            response.setMessage("mail send to : " + request);
            response.setStatus(Boolean.TRUE);

        } catch (MessagingException | IOException | TemplateException e) {
            response.setMessage("Mail Sending failure : "+e.getMessage());
            response.setStatus(Boolean.FALSE);
        }

        return response;
    }
}

Enter fullscreen mode Exit fullscreen mode

here we see. I created a email template page in template folder in springboot application named emailtemplate.ftl extension.



<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Java Techie Mail</title>
</head>

<body>
    <table width="100%" border="0" cellspacing="0" cellpadding="0">
        <tr>
            <td align="center" valign="top" bgcolor="#838383"
                style="background-color: #838383;"><br> <br>
                <table width="600" border="0" cellspacing="0" cellpadding="0">
                    <tr>
                        <td align="center" valign="top" bgcolor="#d3be6c"
                            style="background-color: #d3be6c; font-family: Arial, Helvetica, sans-serif; font-size: 13px; color: #000000; padding: 0px 15px 10px 15px;">

                            <div style="font-size: 48px; color:blue;">
                                <b>Riyas Hacked</b>
                            </div>

                            <div style="font-size: 24px; color: #555100;">
                                <br> Sending Email using Spring Boot with <b>FreeMarker
                                    template !!! <br>
                            </div>
                            <div>
                                <h1>He fucked you${Name} , ${location}</h1>
                            </div>
                        </td>
                    </tr>
                </table> <br> <br></td>
        </tr>
    </table>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

after email send successfully. iam just displaying the success message

<!DOCTYPE html>
<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <h1>send successfully ...........</h1>
    </body>
</html>

Enter fullscreen mode Exit fullscreen mode

Application Properties

spring.mail.default-encoding=UTF-8
spring.mail.host=smtp.gmail.com
spring.mail.username=your e-mail id
spring.mail.password=e-mail id password
spring.mail.port=587
spring.mail.protocol=smtp
spring.mail.test-connection=false
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true

Enter fullscreen mode Exit fullscreen mode

I hope you get an idea to make your own application. please ask queries and give suggestion through muhammedriyas6262@gmail.com

Top comments (0)