Spring boot email sending function

Email sending is a very common function. It is used for identity authentication during registration, sending important notifications, etc. Sun provides JavaMail to implement email sending, but the configuration is cumbersome. Spring provides JavaMailSender to simplify email configuration, and Spring Boot provides MailSenderAutoConfiguration further simplifies email sending. This article will introduce how Spring Boot implements the email sending function.

1. Environment configuration

1. Import dependencies

Use Maven to introduce spring-boot-starter-mail dependency into the project

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2. Add configuration information

After introducing the dependencies, add the following configuration in the application.properties file:

# smtp server host address
spring.mail.host=smtp.xxx.com
# smtp server port number
spring.mail.port=xxx
# Provide email account for sending email service
[email protected]
# Provide email authorization code (such as: qq, 163)/password (such as: Gmail) for sending email services
spring.mail.password=xxxxxxxxxxx
#Default character set
spring.mail.default-encoding=UTF-8
# Whether to enable permission verification
spring.mail.properties.mail.smtp.auth=true
# Whether to enable SSL verification
spring.mail.properties.mail.smtp.ssl.enable=true
# Whether to enable debug mode
spring.mail.properties.mail.debug=true

Remarks

  • SMTP (Simple Mail Transfer Protocol) defines the communication rules between the mail client software and the SMTP server, and between the SMTP server and the SMTP server.
  • The email authorization code needs to be provided by the email service provider after the POP3/SMTP service is enabled on the account.

2. Writing service classes

1. MailService interface

package cn.frankfang.service;

import java.io.File;

/**
 * Interface class of mail service
 *
 * @author Frank Fang
 *
 */
public interface MailService {

    /**
     * Send simple emails
     *
     * @param to recipient
     * @param cc cc person
     * @param subject subject
     * @param content content
     */
    void sendSimpleMall(String to, String subject, String content);

    /**
     * Send emails with attachments
     *
     * @param to recipient
     * @param subject subject
     * @param content content
     * @param file file
     */
    void sendAttachFileMail(String to, String subject, String content, File file);

    /**
     * Send emails in HTML format
     *
     * @param to recipient
     * @param subject subject
     * @param content content
     */
    void sendHtmlMail(String to, String subject, String content);
}

2. MailService implementation class

package cn.frankfang.service.impl;

import java.io.File;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import cn.frankfang.service.MailService;

@Service
public class MailServiceImpl implements MailService{

    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private JavaMailSender mailSender;

    //Send simple email
    @Override
    public void sendSimpleMall(String to, String subject, String content) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();

            message.setFrom(from);
            message.setTo(to);
            message.setCc(from);
            message.setSubject(subject);
            message.setText(content);

            mailSender.send(message);
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }

    //Send email with attachments
    @Override
    public void sendAttachFileMail(String to, String subject, String content, File file) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
            //Email sender
            messageHelper.setFrom(from);
            //Email recipient
            messageHelper.setTo(to);
            //Email Subject
            message.setSubject(subject);
            //content of email
            messageHelper.setText(content);
            //Add attachments
            messageHelper.addAttachment(file.getName(), file);
            //send
            mailSender.send(message);

        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    //Send HTML format file
    @Override
    public void sendHtmlMail(String to, String subject, String content) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
            //Email sender
            messageHelper.setFrom(from);
            //Email recipient
            messageHelper.setTo(to);
            //Email Subject
            message.setSubject(subject);
            //content of email
            messageHelper.setText(content, true);
            //send
            mailSender.send(message);

        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

3. Send email

The following takes the function of sending verification codes as an example to demonstrate how to send emails

1. Import template engine

For emails with complex formats, if you use strings for HTML splicing, it is not only error-prone, but also difficult to maintain. Using HTML templates can solve this problem well. Use Thymeleaf to build an email template. First add the Thymeleaf dependency. The code is as follows:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2. Configure template engine

Add the following configuration in the application.properties file:

# Turn off thymeleaf cache
spring.thymeleaf.cache=false

3. Write HTML template

Add a file named mailtemplate.html to the project’s resource/templates folder and add the following content:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <title>Email verification</title>
    <meta charset="utf-8">
</head>

<body>
    <!-- Head -->
    <div style="padding: 10px; background-color: #393D49;">
        <h2 style="color: #FFFFFF; margin: 0px;">Frank's Blog</h2>
    </div>
    <!-- Content -->
    <div style="padding-top: 10px; padding-bottom: 10px;">
        <div style="background-color: snow; padding: 20px;">
            <div>
                <h3>Dear user: Hello! </h3>
                <p>Note: You are currently performing a sensitive operation. To ensure the security of your account, we will authenticate you via email.</p>
                <p th:text="${message}"></p>
                <div>
                    <h4>The verification code this time is:</h4>
                    <div style="background-color: #EBEEF5; padding: 10px;">
                        <h3 th:text="${code}"></h3>
                    </div>
                    <h4>Validity period is 5 minutes</h4>
                </div>
                <p style="margin-top: 15px;">Sender: Frank's Blog Security Services</p>
            </div>
        </div>
    </div>
    <!-- Bottom of page -->
    <div style="padding: 10px; text-align: center; background-color: #2F4056;">
        <p style="margin: 0px; color: #FFFFFF;">Copyright ? 2020 <a href="https://www.frankfang.cn/" style="color: #FFFFFF;">www.frankfang.cn </a> All Rights Reserved.</p>
    </div>

</body>

</html>

4. Call the mail service

@RestController
public class VerificationController {
    @Autowired
    private MailService mailService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private TemplateEngine templateEngine;

    @GetMapping("/verify/{username}")
    public Object sendVerificationCode(@PathVariable("username") String key) {
        //recipient
        String to = "[email protected]";
        // Email message content
        String message = "Details: You are trying to log in. If it is not your own behavior, please ignore it!";
        // Randomly generate verification code
        String code = MailCodeUtils.getCode();
        //Save key-value pairs
        redisService.set(key, code);
        // Set expiration time (valid within 5 minutes)
        redisService.expire(key, 60 * 5);
        //Set email content
        Context context = new Context();
        context.setVariable("message", message);
        context.setVariable("code", code);
        String mail = templateEngine.process("mailtemplate.html", context);
        // send email
        mailService.sendHtmlMail(to, "Email Verification Code", mail);
        return new JsonResponse(HttpServletResponse.SC_OK, "Verification code sent successfully!");
    }
}

Remarks

  • RedisService is the Redis service class interface
  • JsonResponse is the encapsulated return data class
  • package com.xiaozuliu.email;
    
    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.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.multipart.MultipartFile;
    import org.thymeleaf.TemplateEngine;
    import org.thymeleaf.context.Context;
    
    import java.io.File;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    
    @Controller
    public class EmailController {
        @Autowired
        private EmailService emailService;
        @Autowired
        private TemplateEngine templateEngine;
        @Autowired
        private DynamicSchedulerService dynamicSchedulerService;
        String regex = "^[A-Za-z0-9 + _.-] + @[A-Za-z0-9.-] + $";
        Pattern pattern = Pattern.compile(regex);
        String fileName = "";
        String dirPath = "";
        String imgName = "";
        String imgPath = "";
        String timehour="";
        String timeminute="";
        String emailusername="";
        String emailtitle="";
        String emailtext="";
        String cron="";
        //text
        @ResponseBody
        @PostMapping("/emailindex/emailText")
        public String emailText(@RequestParam("emailname") String emailname, @RequestParam("title") String title, @RequestParam("text") String text) {
            Matcher matcher = pattern.matcher(emailname);
            if (emailname.equals("")) {
                return "Email is empty, please enter your email";
            } else {
                if (matcher.matches()) {
                    if (text.equals("")) {
                        return "The content is empty, please enter the content";
                    } else {
                        if (text.length() <= 200) {
                            //Call the send plain text email method in emailService
                            emailService.sendSimpleEmail(emailname, title, text);
                            return "Plain text email sent successfully";
                        } else {
                            return "The text content is greater than 200 words, the current number of words:" + text.length() + "Words";
                        }
                    }
                } else {
                    return "The email format is wrong, please re-enter";
                }
            }
        }
        //appendix
        @ResponseBody
        @PostMapping("/emailindex/emailAnnex")
        public String emailAnnex(@RequestParam("file") MultipartFile[] fileUpload, @RequestParam("emailname") String emailname, @RequestParam("title") String title) {
            for (MultipartFile file : fileUpload) {
                //Get file name
                fileName = file.getOriginalFilename();
                //The location where the file is stored after selection
                dirPath = "E:\file";
                File filePath = new File(dirPath);
                if (!filePath.exists()) {
                    filePath.mkdirs();
                }
                try {
                    file.transferTo(new File(dirPath + fileName));
                } catch (Exception e) {
                    e.printStackTrace();
                    //Upload failed, return failure information
                }
            }
            Matcher matcher = pattern.matcher(emailname);
            if (emailname.equals("")) {
                return "Email is empty, please enter your email";
            } else {
                if (matcher.matches()) {
                    if (fileName.equals("")) {
                        return "Please add attachments";
                    } else {
                        //Call the send attachment email method in emailService
                        emailService.sendComplexEmail(emailname, title, "", dirPath + fileName);
                        return "The attachment email was sent successfully";
                    }
                } else {
                    return "The email format is wrong, please re-enter";
                }
            }
        }
    //picture
        @ResponseBody
        @PostMapping("/emailindex/emailImg")
        public String emailImg(@RequestParam("img") MultipartFile[] fileUpload, @RequestParam("emailname") String emailname, @RequestParam("title") String title) {
            for (MultipartFile file : fileUpload) {
                //Get the picture name
                imgName = file.getOriginalFilename();
                //The path to store the image after selecting it
                imgPath = "E:\Tp";
                File filePath = new File(imgPath);
                if (!filePath.exists()) {
                    filePath.mkdirs();
                }
                try {
                    file.transferTo(new File(imgPath + imgName));
                } catch (Exception e) {
                    e.printStackTrace();
                    //Upload failed, return failure information
                }
            }
            Matcher matcher = pattern.matcher(emailname);
            //Get the image suffix name
            String suffix = imgName.substring(imgName.lastIndexOf(".") + 1);
            if (emailname.equals("")){
                return "Email is empty, please enter your email";
            }else {
                if (matcher.matches()){
                    if (imgName.equals("")){
                        return "Please add pictures";
                    }else {
                        if (suffix.equalsIgnoreCase("jpg") || suffix.equalsIgnoreCase("png") || suffix.equalsIgnoreCase("bmp") || suffix.equalsIgnoreCase("jpeg")) {
                            StringBuilder text = new StringBuilder();
                            text.append("<html><head></head>");
                            text.append("<body>");
                            String rscId = "img001";
                            text.append("<img src='cid:" + rscId + "'/></body>");text.append("</html>");
                            //Call the send picture email method in emailService
                            emailService.sendComplexEmail(emailname,title,text.toString(), rscId,imgPath + imgName);
                            //Call back to the file upload page with upload status information
                            return "Picture email sent successfully";
                        }else {
                            return "The image format is wrong, please add it again";
                        }
                    }
                }else {
                    return "The email format is wrong, please re-enter";
                }
            }
        }
    //template
        @ResponseBody
        @PostMapping("/emailindex/emailTemplate")
        public String emailTemplate(@RequestParam("emailname") String emailname,@RequestParam("title") String title,@RequestParam("name") String name,@RequestParam("yanzhengma") String yzm) {
            Matcher matcher = pattern.matcher(emailname);
            if (emailname.equals("")){
                return "Email is empty, please enter your email";
            }else {
                if (matcher.matches()){
                    if (name.equals("")){
                        return "Please enter username";
                    }else {
                        Context context = new Context();
                        //Assign value to front-end th:text = ${username}
                        context.setVariable("username", name);
                        //Assign value to front-end th:text = ${code}
                        context.setVariable("code", yzm);
                        String emailContent = templateEngine.process("email/emailverify", context);
                        //Call the send template email method in emailService
                        emailService.sendTemplateEmail(emailname,title,emailContent);
                        return "Template email sent successfully";
                    }
                }else {
                    return "The email format is wrong, please re-enter";
                }
            }
        }
    //timing
        @ResponseBody
        @PostMapping("/emailindex/emailTiming")
        public String emailTiming(@RequestParam("emailname")String emailname,@RequestParam("title") String title,@RequestParam("text") String text,@RequestParam("week")String day,@RequestParam("time" ) String time){
            Matcher matcher = pattern.matcher(emailname);
            //Global variable gets the title
            emailtitle=title;
            if (emailname.equals("")) {
                return "Email is empty, please enter your email";
            }else {
                if (matcher.matches()) {
                    //Global variable gets email
                    emailusername=emailname;
                    if (text.equals("")) {
                        return "The content is empty, please enter the content";
                    }else {
                        if (text.length() <= 200) {
                            //Global variable gets text content
                            emailtext=text;
                            if (day.equals("0")){
                                return "Please select the week you want to set";
                            }else {
                                if (time.equals("")){
                                    return "Please select the time you want to set";
                                }else {
                                    //Global variable gets the hour
                                    timehour = time.substring(0,time.lastIndexOf(":"));
                                    //Global variable gets minutes
                                    timeminute = time.substring(time.lastIndexOf(":") + 1);
                                    //Get new cron expression
                                    cron = "0 " + timeminute + " " + timehour + " * * " + day;
                                    //Call methods within dynamicSchedulerService
                                    dynamicSchedulerService.startScheduledTask(cron);
                                    return "Set scheduled task completed";
                                }
                            }
                        } else {
                            return "The text content is greater than 200 words, the current number of words:" + text.length() + "Words";
                        }
                    }
                }else {
                    return "The email format is wrong, please re-enter";
                }
            }
        }
    }
    

5. Test

Start the server and send a request to the server. The results are as follows:

Test Results

The test is successful when the recipient’s mailbox receives the email with the above content.

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeHomepageOverview 139089 people are learning the system