天天熱點(diǎn)!SpringBoot整合郵件服務(wù)

2022-12-12 12:10:33 來源:51CTO博客


【資料圖】

SpringBoot整合郵件服務(wù)

配置

登錄到QQ郵箱:??https://mail.qq.com/??

選擇賬戶

點(diǎn)擊開啟SMTP服務(wù):

發(fā)送短信:

發(fā)送完,點(diǎn)擊我已發(fā)送,然后得到密碼:

POM依賴:

  org.springframework.boot  spring-boot-starter-mail

application.yml

spring:  mail:    # 配置 SMTP 服務(wù)器地址     host: smtp.qq.com    # 發(fā)送者郵箱    username: 你的郵箱    # 配置密碼,注意不是真正的密碼,而是剛剛申請(qǐng)到的授權(quán)碼    password: 申請(qǐng)的密碼    # 端口號(hào)465或587    port: 587     # 默認(rèn)的郵件編碼為UTF-8    default-encoding: UTF-8

Java集成EmailService

import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.mail.javamail.JavaMailSender;import org.springframework.mail.javamail.MimeMessageHelper;import org.springframework.stereotype.Component;import javax.mail.MessagingException;import javax.mail.internet.MimeMessage;import java.util.Date;@Component@Slf4jpublic class EmailUtils {    @Autowired    JavaMailSender javaMailSender;    @Value("${spring.mail.username}")    String username;    public void sendHtml(String title, String html, String to) {        MimeMessage mailMessage = javaMailSender.createMimeMessage();        //需要借助Helper類        MimeMessageHelper helper = new MimeMessageHelper(mailMessage);        try {            helper.setFrom(username);  // 必填            helper.setTo(to);   // 必填//            helper.setBcc("密送人");   // 選填            helper.setSubject(title);  // 必填            helper.setSentDate(new Date());//發(fā)送時(shí)間            helper.setText(html, true);   // 必填  第一個(gè)參數(shù)要發(fā)送的內(nèi)容,第二個(gè)參數(shù)是不是Html格式。            javaMailSender.send(mailMessage);        } catch (MessagingException e) {            log.error("發(fā)送郵件失敗", e);        }    }}

在controller里定義接口:

@ApiOperation(value = "郵箱驗(yàn)證接口")@GetMapping("/email")public Result sendEmail(@RequestParam String email, @RequestParam String type) {    userService.sendEmail(email, type);    return Result.success();}

在業(yè)務(wù)實(shí)現(xiàn)層UserServiceImpl寫業(yè)務(wù)邏輯

void sendEmail(String email, String type);private static final Map CODE_MAP = new ConcurrentHashMap();@ResourceEmailUtils emailUtils;@Overridepublic void sendEmail(String email, String type) {  String  code = RandomUtil.randomNumbers(6);  log.info("本次驗(yàn)證碼的code是:{}", code);  String context = "尊敬的用戶:


您好," + "Partner交友網(wǎng)提醒您本次的驗(yàn)證碼是:{}," + "有效期5分鐘。


Partner交友網(wǎng)"; String html = StrUtil.format(context, code); if ("REGISTER".equals(type)) { // 多線程異步請(qǐng)求 ThreadUtil.execAsync(() -> { emailUtils.sendHtml("【partner交友網(wǎng)】郵箱注冊(cè)驗(yàn)證",html, email); }); CODE_MAP.put(code, System.currentTimeMillis()); }}

輸入郵箱,點(diǎn)擊發(fā)送:

在后端我們可以看到驗(yàn)證碼為:

登錄郵箱:查看郵件即可

標(biāo)簽: 需要借助 服務(wù)器地址 發(fā)送郵件

上一篇:世界通訊!Modbus入門知識(shí)
下一篇:【Shell腳本(四) -- 流程控制】