Spring Boot实现发送邮件案例

wen java案例 2

本文目录导读:

Spring Boot实现发送邮件案例

  1. 项目依赖配置
  2. 配置文件
  3. 核心代码实现
  4. 配置类
  5. 使用方法示例
  6. 测试类
  7. 邮件服务器配置参考
  8. 注意事项
  9. 完整示例代码

我将为您提供一个完整的Spring Boot发送邮件案例,包括基本配置、纯文本邮件、HTML邮件、附件邮件等常见场景。

项目依赖配置

Maven依赖(pom.xml)

<dependencies>
    <!-- Spring Boot Starter Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- Spring Boot Starter Mail -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>
    <!-- 可选:模板引擎用于HTML邮件 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
</dependencies>

配置文件

application.yml

spring:
  mail:
    host: smtp.qq.com
    port: 587
    username: your_email@qq.com
    password: your_email_password  # QQ邮箱使用授权码
    default-encoding: UTF-8
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
          connectiontimeout: 5000
          timeout: 3000
          writetimeout: 5000
# 自定义邮件配置
mail:
  from: "发送者名称 <your_email@qq.com>"
  to: "recipient@example.com"
  subject: "测试邮件主题"

核心代码实现

1 邮件服务接口

package com.example.mail.service;
import javax.mail.MessagingException;
import java.io.File;
import java.util.Map;
public interface MailService {
    // 发送简单文本邮件
    void sendSimpleMail(String to, String subject, String content);
    // 发送HTML邮件
    void sendHtmlMail(String to, String subject, String content) throws MessagingException;
    // 发送带附件的邮件
    void sendAttachmentMail(String to, String subject, String content, String filePath) throws MessagingException;
    // 发送带图片的HTML邮件
    void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId) throws MessagingException;
    // 使用模板发送邮件
    void sendTemplateMail(String to, String subject, Map<String, Object> templateModel) throws MessagingException;
}

2 邮件服务实现类

package com.example.mail.service.impl;
import com.example.mail.service.MailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.web.multipart.MultipartFile;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Map;
@Service
public class MailServiceImpl implements MailService {
    private static final Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private TemplateEngine templateEngine;
    @Value("${spring.mail.username}")
    private String from;
    @Value("${mail.from}")
    private String mailFrom;
    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        try {
            mailSender.send(message);
            logger.info("简单邮件已发送");
        } catch (Exception e) {
            logger.error("发送简单邮件时发生异常", e);
            throw new RuntimeException("发送邮件失败", e);
        }
    }
    @Override
    public void sendHtmlMail(String to, String subject, String content) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true); // true表示HTML格式
        try {
            mailSender.send(message);
            logger.info("HTML邮件已发送");
        } catch (Exception e) {
            logger.error("发送HTML邮件时发生异常", e);
            throw new RuntimeException("发送HTML邮件失败", e);
        }
    }
    @Override
    public void sendAttachmentMail(String to, String subject, String content, String filePath) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);
        // 添加附件
        FileSystemResource file = new FileSystemResource(new File(filePath));
        String fileName = file.getFilename();
        helper.addAttachment(fileName, file);
        try {
            mailSender.send(message);
            logger.info("带附件邮件已发送");
        } catch (Exception e) {
            logger.error("发送带附件邮件时发生异常", e);
            throw new RuntimeException("发送带附件邮件失败", e);
        }
    }
    @Override
    public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);
        // 添加图片资源
        FileSystemResource res = new FileSystemResource(new File(rscPath));
        helper.addInline(rscId, res);
        try {
            mailSender.send(message);
            logger.info("带图片HTML邮件已发送");
        } catch (Exception e) {
            logger.error("发送带图片HTML邮件时发生异常", e);
            throw new RuntimeException("发送带图片HTML邮件失败", e);
        }
    }
    @Override
    public void sendTemplateMail(String to, String subject, Map<String, Object> templateModel) throws MessagingException {
        Context context = new Context();
        context.setVariables(templateModel);
        // 使用Thymeleaf模板
        String emailContent = templateEngine.process("emailTemplate", context);
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(emailContent, true);
        try {
            mailSender.send(message);
            logger.info("模板邮件已发送");
        } catch (Exception e) {
            logger.error("发送模板邮件时发生异常", e);
            throw new RuntimeException("发送模板邮件失败", e);
        }
    }
    // 支持MultipartFile附件的方法
    public void sendMailWithAttachment(String to, String subject, String content, MultipartFile attachment) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);
        // 添加MultipartFile附件
        helper.addAttachment(attachment.getOriginalFilename(), attachment);
        try {
            mailSender.send(message);
            logger.info("邮件已发送,包含附件: {}", attachment.getOriginalFilename());
        } catch (Exception e) {
            logger.error("发送邮件时发生异常", e);
            throw new RuntimeException("发送邮件失败", e);
        }
    }
}

3 邮件控制器

package com.example.mail.controller;
import com.example.mail.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/mail")
public class MailController {
    @Autowired
    private MailService mailService;
    // 发送简单邮件
    @PostMapping("/simple")
    public String sendSimpleMail(@RequestParam String to,
                                 @RequestParam String subject,
                                 @RequestParam String content) {
        mailService.sendSimpleMail(to, subject, content);
        return "简单邮件发送成功!";
    }
    // 发送HTML邮件
    @PostMapping("/html")
    public String sendHtmlMail(@RequestParam String to,
                               @RequestParam String subject,
                               @RequestParam String content) {
        try {
            mailService.sendHtmlMail(to, subject, content);
            return "HTML邮件发送成功!";
        } catch (Exception e) {
            return "邮件发送失败: " + e.getMessage();
        }
    }
    // 发送带附件的邮件
    @PostMapping("/attachment")
    public String sendAttachmentMail(@RequestParam String to,
                                     @RequestParam String subject,
                                     @RequestParam String content,
                                     @RequestParam String filePath) {
        try {
            mailService.sendAttachmentMail(to, subject, content, filePath);
            return "带附件邮件发送成功!";
        } catch (Exception e) {
            return "邮件发送失败: " + e.getMessage();
        }
    }
    // 发送带文件的邮件(从客户端上传文件)
    @PostMapping("/upload")
    public String sendMailWithUpload(@RequestParam String to,
                                     @RequestParam String subject,
                                     @RequestParam String content,
                                     @RequestParam("file") MultipartFile file) {
        try {
            MailServiceImpl impl = (MailServiceImpl) mailService;
            impl.sendMailWithAttachment(to, subject, content, file);
            return "带附件邮件发送成功!";
        } catch (Exception e) {
            return "邮件发送失败: " + e.getMessage();
        }
    }
    // 发送模板邮件
    @PostMapping("/template")
    public String sendTemplateMail(@RequestParam String to,
                                   @RequestParam String subject) {
        try {
            Map<String, Object> templateModel = new HashMap<>();
            templateModel.put("name", "张三");
            templateModel.put("message", "这是一个模板测试邮件");
            mailService.sendTemplateMail(to, subject, templateModel);
            return "模板邮件发送成功!";
        } catch (Exception e) {
            return "邮件发送失败: " + e.getMessage();
        }
    }
    // 测试发送简单邮件
    @GetMapping("/test")
    public String testSend() {
        try {
            mailService.sendSimpleMail("recipient@example.com", "测试邮件", "这是测试内容");
            return "测试邮件发送成功!";
        } catch (Exception e) {
            return "邮件发送失败: " + e.getMessage();
        }
    }
}

4 Thymeleaf模板文件

创建 src/main/resources/templates/emailTemplate.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">邮件模板</title>
</head>
<body>
    <div style="padding: 20px; background-color: #f5f5f5;">
        <h1>你好, <span th:text="${name}"></span>!</h1>
        <p th:text="${message}"></p>
        <hr>
        <footer>
            <p>这是一封自动发送的邮件, 请勿回复。</p>
        </footer>
    </div>
</body>
</html>

配置类

package com.example.mail.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import java.util.Properties;
@Configuration
public class MailConfig {
    @Bean
    public JavaMailSender javaMailSender() {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost("smtp.qq.com");
        mailSender.setPort(587);
        mailSender.setUsername("your_email@qq.com");
        mailSender.setPassword("your_email_password");
        Properties props = mailSender.getJavaMailProperties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.connectiontimeout", "5000");
        props.put("mail.smtp.timeout", "3000");
        props.put("mail.smtp.writetimeout", "5000");
        return mailSender;
    }
}

使用方法示例

1 在Service中使用

@Service
public class UserService {
    @Autowired
    private MailService mailService;
    public void registerUser(String email, String username) {
        // 业务逻辑
        // 发送注册成功邮件
        String subject = "注册成功通知";
        String content = String.format("亲爱的%s,恭喜您注册成功!", username);
        try {
            mailService.sendHtmlMail(email, subject, 
                "<h2>欢迎注册</h2><p>" + content + "</p>");
        } catch (Exception e) {
            // 邮件发送失败,但注册可能成功,需要异步处理
            log.error("发送注册邮件失败", e);
        }
    }
}

2 异步发送邮件

package com.example.mail.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncMailService {
    @Autowired
    private MailService mailService;
    @Async
    public void sendAsyncMail(String to, String subject, String content) {
        mailService.sendSimpleMail(to, subject, content);
    }
}

测试类

package com.example.mail;
import com.example.mail.service.MailService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class MailApplicationTests {
    @Autowired
    private MailService mailService;
    @Test
    void sendSimpleMailTest() {
        mailService.sendSimpleMail(
            "recipient@example.com",
            "测试简单邮件",
            "这是一封测试邮件"
        );
    }
    @Test
    void sendHtmlMailTest() throws Exception {
        String content = "<html><body>"
            + "<h2>HTML邮件测试</h2>"
            + "<p>这是一封<strong>HTML</strong>格式的邮件</p>"
            + "</body></html>";
        mailService.sendHtmlMail("recipient@example.com", "HTML邮件", content);
    }
}

邮件服务器配置参考

常见邮箱SMTP配置:

邮箱 SMTP服务器 SSL端口 需要设置
QQ邮箱 smtp.qq.com 465/587 授权码(非密码)
163邮箱 smtp.163.com 465/994 客户端授权密码
Gmail smtp.gmail.com 587 应用专用密码
Outlook smtp-mail.outlook.com 587 密码

注意事项

  1. 配置授权码:QQ、163等邮箱需要使用授权码而不是邮箱密码
  2. 安全协议:建议使用SSL/TLS加密连接
  3. 发送限制:多数邮箱服务商有每日发送数量限制
  4. 编码问题:确保邮件内容正确编码,UTF-8
  5. 异步处理:建议使用异步方式发送邮件避免阻塞主流程
  6. 异常处理:发送失败时要添加重试机制和错误日志

完整示例代码

完整的项目结构:

src/main/java/com/example/mail/
├── MailApplication.java
├── config/
│   └── MailConfig.java
├── controller/
│   └── MailController.java
├── service/
│   ├── MailService.java
│   ├── AsyncMailService.java
│   └── impl/
│       └── MailServiceImpl.java
└── resources/
    ├── application.yml
    └── templates/
        └── emailTemplate.html

这个案例涵盖了Spring Boot发送邮件的所有常见场景,包括简单文本、HTML、附件、模板等,您可以根据实际需求选择合适的实现方式。

抱歉,评论功能暂时关闭!