1,添加核心依赖

<!-- 邮箱服务 -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2,添加配置

spring:
  mail:
    host: 6.tcp.vip.cpolar.cn
    port: 10572
    username: xxx@loren.com
    password: 123456  # 使用应用专用密码
    default-encoding: UTF-8 # 配置邮件编码
    properties:
      mail:
        smtp:
          auth: false
          starttls:
            enable: false
          debug: true

3,在resources目录下创建templates目录,旗下创建模板email-template.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <body>
        <h1 th:text="${title}">Default Title</h1>
        <p th:text="${message}">Default Message</p>
    </body>
</html>

4,编写核心service代码

package org.example.service.service;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.example.model.req.EmailRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

@Service
@Slf4j
public class MailService {
    @Value("${spring.mail.username}")
    private String from;
    private final JavaMailSender mailSender;
    private final TemplateEngine templateEngine;
    public MailService(JavaMailSender mailSender, TemplateEngine templateEngine) {
        this.mailSender = mailSender;
        this.templateEngine = templateEngine;
    }
    public void testConnection() {
        try {
            ((JavaMailSenderImpl) mailSender).testConnection();
            log.info("邮件服务器连接成功");
        } catch (MessagingException e) {
            log.error("邮件服务器连接失败: {}", e.getMessage(), e);
        }
    }
    // 发送纯文本邮件
    public void sendSimpleMail(String to, String subject, String content) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            message.setTo(to);
            message.setSubject(subject);
            message.setText(content);
            mailSender.send(message);
            log.info("邮件发送成功: 收件人={}, 主题={}", to, subject);
        } catch (Exception e) {
            log.error("邮件发送失败: 收件人={}, 主题={}, 错误={}", to, subject, e.getMessage(), e);
        }
    }
    // 发送HTML邮件(带模板)
    public void sendTemplateMail(EmailRequest request) {
        try {
            Context context = new Context();
            context.setVariable("title", request.getTitle());
            context.setVariable("message", request.getMessage());
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(from);
            helper.setTo(request.getTo());
            helper.setSubject(request.getSubject());
            String htmlContent = templateEngine.process("email-template", context);
            helper.setText(htmlContent, true);
            mailSender.send(mimeMessage);
            log.info("HTML邮件发送成功: 收件人={}, 主题={}", request.getTo(), request.getSubject());
        } catch (MessagingException e) {
            log.error("HTML邮件发送失败: 收件人={}, 主题={}, 错误={}", request.getTo(), request.getSubject(), e.getMessage(), e);
        }
    }
}

编写核心实体类EmailRequest

package org.example.model.req;

import lombok.Data;

@Data
public class EmailRequest {
    private String to;
    private String subject;
    private String title;
    private String message;
}

5,编写controller

package org.example.controller;

import org.example.model.req.EmailRequest;
import org.example.service.service.MailService;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/email")
public class MailController {
    private final MailService mailService;
    public MailController(MailService mailService) {
        this.mailService = mailService;
    }
    @GetMapping("/testConnection")
    public String testConnection() {
        mailService.testConnection();
        return "success";
    }
    @PostMapping("/send-email")
    public String sendEmail(@RequestBody EmailRequest request) {
        mailService.sendTemplateMail(request);
        return "Email sent successfully!";
    }
}

关于邮箱服务器配置有两种方式: 1,使用QQ邮箱 2,本地搭建邮箱服务

1,使用QQ邮箱服务 网页登录QQ邮箱 设置-》服务状态(开启)-》获取授权码(配置中的密码就是这里的授权码,不能用登录密码) 以上设置完之后的配置为如下:

spring:
  mail:
    host: smtp.qq.com
    port: 587
    username: xxx@qq.com
    password: xxx  # 使用应用专用密码
    default-encoding: UTF-8 # 配置邮件编码
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
          debug: true

2,搭建本地邮箱服务器 主要使用免费开源的hmailServer,下载地址: https://www.hmailserver.com/download 需要在安装hmailserver之前下载安装 .net framework2.0,否则会安装hmailserver失败,地址: https://www.microsoft.com/zh-cn/download/details.aspx?id=16614 下载安装完hmailserver后,设置domains,添加Accounts 就可以使用了 可以下载安装foxmail进行登录,地址: Foxmail for Mac 如果想要使用内网穿透工具,可以下载cpolar,地址: download下载 - cpolar 极点云官网 配置为:

spring:
  mail:
    host: 127.0.0.1
    port: 110
    username: hello@loren.com
    password: 123456  # 使用应用专用密码
    default-encoding: UTF-8 # 配置邮件编码
    properties:
      mail:
        smtp:
          auth: false
          starttls:
            enable: false
          debug: true

spring:
  mail:
    host: 6.tcp.vip.cpolar.cn
    port: 10572
    username: hello@loren.com
    password: 123456  # 使用应用专用密码
    default-encoding: UTF-8 # 配置邮件编码
    properties:
      mail:
        smtp:
          auth: false
          starttls:
            enable: false
          debug: true

参照文档: 使用hMailServer 搭建个人邮件服务器(小白教程) - Book鱼 - 博客园

测试请求参数body:

{
  "to": "2415612109@qq.com",
  "subject": "测试邮件",
  "title": "Hello-测试",
  "message": "你好,This is a test email from Spring Boot!"
}

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐