SpringBoot發送html郵箱驗證碼功能

1. 效果展示(用戶收到的)

2. 郵件推送管理(見以後的博客)

先看看如果管理員手動發送該如何操作


3. 後端核心代碼(通用版)

3.1 SendEmailVO實體類

package com.example.han.model.VO;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Map;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Schema(description = "發送郵件VO實體類")
public class SendEmailVO {
    @Schema(description = "收件人郵箱")
    String toAddress;
    @Schema(description = "模板名")
    String modelName;
    @Schema(description = "郵件標題")
    String title;
    @Schema(description = "文本裡所需要參數")
    Map<String,String> parameters;
    @Schema(description = "調用者類型(管理員/服務)")
    String manageType;
    @Schema(description = "(調用者/服務)名稱")
    String manager;
}

3.2 Controller層核心代碼

   @Operation(summary = "發送html郵件")
   @PutMapping("/sendemail")
   public ResultReturn sendEmail(@RequestBody SendEmailVO sendEmailVO){
       return (sendModelService.sendEmailByParam(sendEmailVO));
   }

3.3 ServiceImpl層核心代碼

    @Autowired
    HtmlEmailServiceImpl htmlEmailService;
    
    /**
     * 通過模板名查找html文本
     * @param name 模板名
     * @return 返回html文本
     */
    public String getTextByName(String name){
        List<MailModelDO> lists = mailRepository.getAllMailModel();
        for (MailModelDO list : lists){
            if(list.getModelName().equals(name)){
                return list.getHtmlText();
            }
        }
        return "NOT FOUND";
    }
    /**
     * 發送郵件的操作
     * @param sendEmailVO 發送郵件VO實體類
     * @return 收件人郵箱
     */
    public ResultReturn sendEmailByParam(SendEmailVO sendEmailVO){
        String str = getTextByName(sendEmailVO.getModelName());
        if(!CheckMail.checkMail(sendEmailVO.getToAddress())){
            return ResultReturnUtil.fail(WRONG_EMAIL_ADDRESS);
        }
        if(sendEmailVO.getTitle().equals("")){
            return ResultReturnUtil.fail(EMPTY_TITLE);
        }
        if(str.equals("NOT FOUND")){
            return ResultReturnUtil.fail(FIND_MODEL_FAILED);
        }
        ReplaceWordUtil replaceWordUtil = new ReplaceWordUtil();
        String content = replaceWordUtil.replaceWord(str,sendEmailVO.getParameters());

        MailInfoTO info = new MailInfoTO();
        info.setToAddress(sendEmailVO.getToAddress());
        info.setSubject(sendEmailVO.getTitle());
        info.setContent(content);
        try {
            htmlEmailService.sendHtmlMail(info);
        } catch (Exception e) {
            //System.out.print("'"+sendEmailVO.getTitle()+"'的郵件發送失敗!");
            e.printStackTrace();
        }
        MailHistoryDO mailHistoryDO = ToBeMailHistoryDO(sendEmailVO);
        mailRepository.saveHistory(mailHistoryDO);
        return ResultReturnUtil.success(SEND_EMAIL_SUCCESS,sendEmailVO.getToAddress());
    }

3.4 利用正則檢查郵箱是否合法工具類

package com.example.han.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CheckMail {
    public static boolean checkMail(String mail){
        Pattern pattern=Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
        //\w+@(\w+.)+[a-z]{2,3}
        Matcher matcher=pattern.matcher(mail);
        return matcher.matches();
    }
}

3.5 字符替換工具類

就是為瞭將模板中的花括號替換成真正需要的東西

package com.example.han.util;

import java.util.Iterator;
import java.util.Map;

/**
 * 將str通過map的key轉換成value
 */
public class ReplaceWordUtil {
    public String replaceWord(String str, Map<String,String> map) {
        Iterator iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            Object key = entry.getKey();
            Object value = entry.getValue();
            str = str.replace("{{"+key+"}}",value+"");
            //System.out.println(key+":"+value);
        }
        //System.out.println(str);
        return str;
    }
}

3.6 Reposity層 邏輯並不是很好,是找出來所有模版以後,開始遍歷出來想要的那一個

package com.example.han.repository;

import com.example.han.model.DO.MailHistoryDO;
import com.example.han.model.DO.MailModelDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class MailRepository {
    @Autowired
    MongoTemplate mongoTemplate;

    public List<MailModelDO> getAllMailModel(){
        System.out.println(mongoTemplate.findAll(MailModelDO.class));
        return mongoTemplate.findAll(MailModelDO.class);
    }
}

3.7 發送html郵件的核心配置類

package com.example.han.service.impl;

import com.example.han.model.TO.MailInfoTO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Date;
import java.util.Properties;


@Service
public class HtmlEmailServiceImpl{
    @Value("${spring.mail.host}")
    private String host;

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

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

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

    /**
     * 發送html郵件
     * @param info MailInfo實體類
     * @throws Exception 拋出異常
     */
    public void sendHtmlMail(MailInfoTO info) throws Exception {
        System.out.println(host);
        System.out.println(formName);
        info.setHost(host);
        info.setFormName(formName);
        info.setFormPassword(password);   //網易郵箱的授權碼~不一定是密碼
        info.setReplayAddress(replayAddress);
        System.out.println(info.getHost());
        System.out.println(info.getContent());

        Message message = getMessage(info);
        // MiniMultipart類是一個容器類,包含MimeBodyPart類型的對象
        Multipart mainPart = new MimeMultipart();
        // 創建一個包含HTML內容的MimeBodyPart
        BodyPart html = new MimeBodyPart();
        // 設置HTML內容
        html.setContent(info.getContent(), "text/html; charset=utf-8");
        mainPart.addBodyPart(html);
        // 將MiniMultipart對象設置為郵件內容
        message.setContent(mainPart);
        Transport.send(message);
    }

    public Message getMessage(MailInfoTO info) throws Exception{
        final Properties p = System.getProperties() ;
        p.setProperty("mail.smtp.host", info.getHost());
        p.setProperty("mail.smtp.auth", "true");
        p.setProperty("mail.smtp.user", info.getFormName());
        p.setProperty("mail.smtp.pass", info.getFormPassword());

        // 根據郵件會話屬性和密碼驗證器構造一個發送郵件的session
        Session session = Session.getInstance(p, new Authenticator(){
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(p.getProperty("mail.smtp.user"),p.getProperty("mail.smtp.pass"));
            }
        });
        session.setDebug(true);
        Message message = new MimeMessage(session);
        //消息發送的主題
        message.setSubject(info.getSubject());
        //接受消息的人
        message.setReplyTo(InternetAddress.parse(info.getReplayAddress()));
        //消息的發送者
        message.setFrom(new InternetAddress(p.getProperty("mail.smtp.user"),"這是我的名字"));
        // 創建郵件的接收者地址,並設置到郵件消息中
        message.setRecipient(Message.RecipientType.TO,new InternetAddress(info.getToAddress()));
        // 消息發送的時間
        message.setSentDate(new Date());
        return message ;
    }
}

4. 後端代碼(帶例子版)

4.1 Controller層

    @Operation(summary = "設置並發送忘記密碼的驗證碼")
    @PostMapping("/sendForgetPasswordCode")
    public ResultReturn sendForgetPasswordCode(String email) throws MyException {
        return userService.sendForgetCode(email);
    }

4.2 ServiceImpl層

  • 這裡我都配置到系統裡去瞭,每次就不用管理員手動發送,隻要用戶發個請求,系統就能自動生成並發送驗證碼。
  • 裡面的工具類還有一些方法,可以查閱上面通用版裡面的代碼,這裡我就不贅述瞭。
    @Override
    public ResultReturn sendForgetCode(String email) throws MyException {
        if(!CheckMail.checkMail(email)){
            throw new MyException(400,WRONG_EMAIL_ADDRESS);
        }
        String num = ""+RandomUtil.Code();
        redisUtil.setRedisKey("forgetCode", num, 60*5);    //先存入redis
        SendEmailVO sendEmailVO = new SendEmailVO();
        sendEmailVO.setManageType("System");
        sendEmailVO.setManager("ForgetPasswordSystem");
        sendEmailVO.setModelName("forgetCode");     //需要用的模版名字
        Map map = new HashMap<String,String>();
        map.put("code",num);
        sendEmailVO.setParameters(map);
        sendEmailVO.setTitle("詩雲-忘記密碼-驗證碼");
        sendEmailVO.setToAddress(email);
        sendEmailService.sendEmailByParam(sendEmailVO);
        return ResultReturnUtil.success(SEND_VERIFICATION_CODE_SUCCESS,email);
    }

5. html郵件內容

5.1 註冊驗證碼模板

https://www.jb51.net/article/180220.htm

到此這篇關於SpringBoot發送html郵箱驗證碼的文章就介紹到這瞭,更多相關SpringBoot發送郵箱驗證碼內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: