Hello everyone, in this chapter we add the system to send mail function. If you have any questions, please contact me at [email protected]. Ask for directions of various gods, thank you

This chapter introduces sending regular mail, sending attachments, sending template mail and so on

Add a Mail dependency

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

Two: Add mail configuration

Open the application. The properties

Add the following configuration

spring.mail.protocol=smtp
spring.mail.host=smtp.chuchenkj.xyz  # Change this to your own email type, such as QQ email, write smtp.qq.com
spring.mail.port=25
spring.mail.smtpAuth=true
spring.mail.smtpStarttlsEnable=true
spring.mail.smtpSslTrust=smtp.chuchenkj.xyz   # Change this to your own email type, such as QQ email, write smtp.qq.com
[email protected]  # Change this to your email account
spring.mail.password=****************         # Change your email password or authorization code to baiduCopy the code

Create a mail entity class

package com.example.demo.model; import java.util.Map; Public class Mail {** * private String[] to; /** * cc */ private String[] cc; /** * private String subject; /** * Private String text; */ private Map<String,String> templateModel; */ private Map<String,String> templateModel; /** * Which template is used to send template emails Mandatory */ private String templateName; public String[]getTo() {
        return to;
    }

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

    public String getSubject() {
        return subject;
    }

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

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public Map<String, String> getTemplateModel() {
        return templateModel;
    }

    public void setTemplateModel(Map<String, String> templateModel) {
        this.templateModel = templateModel;
    }

    public String getTemplateName() {
        return templateName;
    }

    public void setTemplateName(String templateName) {
        this.templateName = templateName;
    }

    public String[] getCc() {
        return cc;
    }

    public void setCc(String[] cc) { this.cc = cc; }}Copy the code

Create a mail constant class

To create the core – constant – MailConstant

package com.example.demo.core.constant; Public class MailConstant {/** * public static final String RETGISTEREMPLATE ="register"; Public static final String TEMPLATEPATH = public static final String TEMPLATEPATH ="src/test/java/resources/template/mail";
}
Copy the code

Five: Create the mail business class

MailService

package com.example.demo.service; import com.example.demo.model.Mail; import javax.servlet.http.HttpServletRequest; Public interface MailService {/** * sendSimpleMail * @param mail */ void sendSimpleMail(mail mail); /** * @param mail * @param Request */ void sendAttachmentsMail(mail, HttpServletRequest Request); /** * Send a photo of a static resource * @param mail * @throws Exception */ void sendInlineMail(mail mail) throws Exception; /** * sendTemplateMail(mail mail); }Copy the code

MailServiceImpl

package com.example.demo.service.impl;

import com.example.demo.core.constant.MailConstant;
import com.example.demo.core.utils.UploadActionUtil;
import com.example.demo.model.Mail;
import com.example.demo.service.MailService;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Service
public class MailServiceImpl implements MailService {

    private static final Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);

    @Resource
    @Qualifier("javaMailSender")
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}") private String from; @Resource private FreeMarkerConfigurer freeMarkerConfigurer; @override public void sendSimpleMail(Mail Mail){SimpleMailMessage = new SimpleMailMessage(); message.setFrom(from); message.setTo(mail.getTo()); message.setSubject(mail.getSubject()); message.setText(mail.getText()); message.setCc(mail.getCc()); mailSender.send(message); Throws Exception */ @override public void sendAttachmentsMail(Mail Mail,HttpServletRequest Request){ try{ MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
            helper.setFrom(from);
            helper.setTo(mail.getTo());
            helper.setSubject(mail.getSubject());
            helper.setText(mail.getText());
            List<String> list = UploadActionUtil.uploadFile(request);
            for(int i = 1,length = list.size(); i<=length; i++) { String fileName = list.get(i-1); String fileTyps = fileName.substring(fileName.lastIndexOf("."));
                FileSystemResource file = new FileSystemResource(new File(fileName));
                helper.addAttachment("The attachment -"+i+fileTyps, file); } mailSender.send(mimeMessage); }catch (Exception e){ e.printStackTrace(); @override public void sendInlineMail(mail mail){try{@override public void sendInlineMail(mail mail){ MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
            helper.setFrom(from);
            helper.setTo(mail.getTo());
            helper.setSubject(mail.getSubject());
            helper.setText("<html><body><img src=\"cid:chuchen\" ></body></html>".true);

            FileSystemResource file = new FileSystemResource(new File("C:\ Users\ Administrator\ Desktop\ Design drawing \ completed \ wechat image _20180323135358.png")); // The resource name chuchen in the addInline function needs to correspond to the cid:chuchen in the body. Helper.addinline ("chuchen", file);
            mailSender.send(mimeMessage);
        }catch (Exception e){
            logger.error("Abnormal sending of mail"); @override public void sendTemplateMail(mail mail){MimeMessage message = null; try { message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message,true); helper.setFrom(from); helper.setTo(mail.getTo()); helper.setSubject(mail.getSubject()); / / read HTML freemarker template. The template. The Configuration of CFG = getConfiguration (); Template template = cfg.getTemplate(mail.getTemplateName()+".ftl");
            String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, mail.getTemplateModel());
            helper.setText(html, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        mailSender.send(message);
    }

    private static freemarker.template.Configuration getConfiguration() throws IOException {
        freemarker.template.Configuration cfg = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_23);
        cfg.setDirectoryForTemplateLoading(new File(MailConstant.TEMPLATEPATH));
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
        returncfg; }}Copy the code

Create an FTL template

Here we create a registered template, other templates you can create your own

In SRC/test/Java/resources/template/mail directory to create the register. The FTL

<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf8">< /head> <body> <div>${to}<div> <span> <span style= "box-sizing: border-box! Important"color: red;">${identifyingCode}</span>
    </span>
</div>
<span style="margin-top: 100px"</span> </body> </ HTML >Copy the code

If you look at this, some of you might be familiar with it, and yes, that’s the method that you used in the article on automatically generating Service controllers

Create a MailController

package com.example.demo.controller;

import com.example.demo.core.constant.MailConstant;
import com.example.demo.core.ret.RetResponse;
import com.example.demo.core.ret.RetResult;
import com.example.demo.core.utils.ApplicationUtils;
import com.example.demo.model.Mail;
import com.example.demo.service.MailService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/mail") public class MailController { @Resource private MailService mailService; /** * Send registration verification code * @param mail * @returnVerification code * @throws Exception */ @postMapping ("/sendTemplateMail")
    public RetResult<String> sendTemplateMail(Mail mail) throws Exception {
        String identifyingCode = ApplicationUtils.getNumStringRandom(6);
        mail.setSubject("Welcome to register early Morning");
        mail.setTemplateName(MailConstant.RETGISTEREMPLATE);
        Map<String,String> map = new HashMap<>();
        map.put("identifyingCode",identifyingCode);
        map.put("to",mail.getTo()[0]);
        mail.setTemplateModel(map);
        mailService.sendTemplateMail(mail);

        return RetResponse.makeOKRsp(identifyingCode);
    }

    @PostMapping("/sendAttachmentsMail")
    public RetResult<String> sendAttachmentsMail(Mail mail,HttpServletRequest request) throws Exception {
        mail.setSubject("Test accessories");
        mailService.sendAttachmentsMail(mail, request);
        returnRetResponse.makeOKRsp(); }}Copy the code

Eight: testing

Enter localhost: 8080 / mail/sendTemplateMail



Open the mail



Enter localhost: 8080 / mail/sendAttachmentsMail






Ok, successful

The project address

Code cloud address: gitee.com/beany/mySpr…

GitHub address: github.com/MyBeany/myS…

Writing articles is not easy, if it is helpful to you, please help click star

At the end

Adding the system to send mail function has been completed, and the subsequent functions will be updated in succession. If you have any questions, please contact me at [email protected]. Ask for directions from various gods, thank you.