從零搭建自己的SpringBoot後臺框架(十七)

Mr_初晨發表於2018-05-29
Hello大家好,本章我們新增系統傳送郵件功能 。有問題可以聯絡我mr_beany@163.com。另求各路大神指點,感謝

本章我們介紹傳送普通郵件,傳送附件,傳送模板郵件等

一:新增mail依賴

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-mail</artifactId>
</dependency>複製程式碼

二:新增郵件配置

開啟application.properties

新增如下配置

spring.mail.protocol=smtp
spring.mail.host=smtp.chuchenkj.xyz  #這裡換成自己的郵箱型別   例如qq郵箱就寫smtp.qq.com
spring.mail.port=25
spring.mail.smtpAuth=true
spring.mail.smtpStarttlsEnable=true
spring.mail.smtpSslTrust=smtp.chuchenkj.xyz   #這裡換成自己的郵箱型別   例如qq郵箱就寫smtp.qq.com
spring.mail.username=chuchenkf@chuchenkj.xyz  #這裡換成自己的郵箱賬號
spring.mail.password=****************         #這裡換成自己的郵箱密碼或授權碼   授權碼獲取可以百度複製程式碼

三:建立郵件實體類

package com.example.demo.model;

import java.util.Map;

public class Mail {

    /**
     * 發給多個人
     */
    private String[] to;

    /**
     * 抄送
     */
    private String[] cc;

    /**
     * 郵件標題
     */
    private String subject;

    /**
     * 郵件內容   簡單文字 和附件郵件必填  其餘的不需要
     */
    private String text;

    /**
     * 模板需要的資料   傳送模板郵件必填
     */
    private Map<String,String> templateModel;

    /**
     * 選用哪個模板 傳送模板郵件必填
     */
    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;
    }
}複製程式碼

四:建立郵件常量類

建立core→constant→MailConstant

package com.example.demo.core.constant;

public class MailConstant {

    /**
     * 註冊的模板名稱
     */
    public static final String RETGISTEREMPLATE = "register";

    /**
     * 模板存放的路徑
     */
    public static final String TEMPLATEPATH = "src/test/java/resources/template/mail";
}
複製程式碼

五:建立郵件業務類

MailService

package com.example.demo.service;

import com.example.demo.model.Mail;

import javax.servlet.http.HttpServletRequest;

public interface MailService {

    /**
     * 傳送簡單郵件
     * @param mail
     */
    void sendSimpleMail(Mail mail);

    /**
     * 傳送帶附件的郵件
     * @param mail
     * @param request
     */
    void sendAttachmentsMail(Mail mail, HttpServletRequest request);

    /**
     * 傳送靜態資源  一張照片
     * @param mail
     * @throws Exception
     */
    void sendInlineMail(Mail mail) throws Exception;

    /**
     * 傳送模板郵件
     * @param mail
     */
    void sendTemplateMail(Mail mail);
}
複製程式碼

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 message = 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("附件-"+i+fileTyps, file);
            }
            mailSender.send(mimeMessage);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 傳送靜態資源  一張照片
     * @param mail
     * @throws Exception
     */
    @Override
    public void sendInlineMail(Mail mail){
        try{
            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\\設計圖\\已完成\\微信圖片_20180323135358.png"));
            // addInline函式中資源名稱chuchen需要與正文中cid:chuchen對應起來
            helper.addInline("chuchen", file);
            mailSender.send(mimeMessage);
        }catch (Exception e){
            logger.error("傳送郵件發生異常");
        }

    }

    /**
     * 傳送模板郵件
     * @param 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());
            //讀取 html 模板
            freemarker.template.Configuration 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);
        return cfg;
    }
}複製程式碼

六:建立ftl模板

這裡我們建立一個註冊的模板,其他模板大家可自行建立

在src/test/java/resources/template/mail目錄下建立register.ftl

<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf8">
</head>
<body>
<div><span>尊敬的</span>${to}:</div>
<div>
    <span>歡迎您加入初晨,您的驗證碼為:
        <span style="color: red;">${identifyingCode}</span>
    </span>
</div>
<span style="margin-top: 100px">初晨科技</span>
</body>
</html>  複製程式碼

看到這裡,可能有的同學就很熟悉,對,這就是自動生成Service,Controller這篇文章裡用到的方法

七:建立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;

    /**
     * 傳送註冊驗證碼
     * @param mail
     * @return 驗證碼
     * @throws Exception
     */
    @PostMapping("/sendTemplateMail")
    public RetResult<String> sendTemplateMail(Mail mail) throws Exception {
        String identifyingCode = ApplicationUtils.getNumStringRandom(6);
        mail.setSubject("歡迎註冊初晨");
        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("測試附件");
        mailService.sendAttachmentsMail(mail, request);
        return RetResponse.makeOKRsp();
    }
}複製程式碼

八:測試

輸入localhost:8080/mail/sendTemplateMail

從零搭建自己的SpringBoot後臺框架(十七)

開啟郵箱

從零搭建自己的SpringBoot後臺框架(十七)

輸入localhost:8080/mail/sendAttachmentsMail

從零搭建自己的SpringBoot後臺框架(十七)


從零搭建自己的SpringBoot後臺框架(十七)

ok,成功

專案地址

碼雲地址: gitee.com/beany/mySpr…

GitHub地址: github.com/MyBeany/myS…

寫文章不易,如對您有幫助,請幫忙點下star從零搭建自己的SpringBoot後臺框架(十七)

結尾

新增系統傳送郵件功能已完成,後續功能接下來陸續更新,有問題可以聯絡我mr_beany@163.com。另求各路大神指點,感謝大家。



相關文章