开发者

SpringBoot整合Email发送的完整配置和实现方法

目录
  • 引言
  • 一、环境准备
    • 1. 添加Maven依赖
    • 2. 配置邮件服务器
  • 二、邮件实体类
    • 三、邮件发送工具类
      • 四、创建邮件模板
        • 1. 注册确认模板(register.html)
      • 五、Controller层实现
        • 六、SpringBoot主程序
          • 七、常见邮件服务器配置
            • 1. QQ邮箱配置
            • 2. 163邮箱配置
            • 3. Gmail配置
          • 八、安全性建议
            • 九、测试示例

              引言

              下面将详细介绍SpringBoot整合Email发送的完整配置和实现方法,包括普通文本邮件、HTML邮件、带附件邮件以及使用模板的邮件发送。

              一、环境准备

              1. 添加Maven依赖

              pom.XML文件中添加邮件发送相关依赖:

              <!-- 邮件发送核心依赖 -->
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-mail</artifactId>
              </dependency>
              
              <!-- 可选:如果需要使用FreeMarker模板 -->
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-freemarker</artifactId>
              </dependency>
              

              2. 配置邮件服务器

              application.yml中配置SMTP服务器信息:

              spring:
                mail:
                  host: smtp.qq.com  # SMTP服务器地址
                  port: 587  # 端口号(QQ邮箱用587,SSL用465)
                  username: your-email@qq.com  # 发件人邮箱
                  password: your-auth-code  # 授权码(非邮箱密码)
                  default-encoding: UTF-8
                  protocol: smtp
                  properties:
                    mail:
                      smtp:
                        auth: true
                        starttls:
                          enable: true
                          required: true
                        ssl:
                          enable: false  # 如果使用465端口则设为true
                      debug: true  # 开发阶段可开启调试模式
              

              注意:需要先在邮箱中开启SMTP服务并获取授权码:

              • QQ邮箱:设置 > 账户 > POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务 > 开启POP3/SMTP服务
              • 163邮箱:设置 > POP3/SMTP/IMAP > 开启SMTP服务
              • 企业邮箱:根据不同服务商的指引开启

              二、邮件实体类

              创建邮件信息的实体类:

              import lombok.Data;
              import Java.io.Serializable;
              
              @Data
              public class MailDTO implements Serializable {
                  private String recipient;  // 收件人邮箱
                  private String[] recipients;  // 多个收件人(可选)
                  private String subject;  // 邮件主题
                  private String content;  // 邮件内容
                  private String templateName;  // 模板名称(可选)
                  private Object templateModel;  // 模板数据模型(可选)
              }
              

              三、邮件发送工具类

              创建一个通用的邮件发送工具类:

              import lombok.extern.slf4j.Slf4j;
              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.Component;
              import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
              import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
              
              import javax.mail.MessagingException;
              import javax.mail.internet.MimeMessage;
              import java.io.File;
              import java.util.Map;
              
              @Component
              @Slf4j
              public class MailService {
              
                  @Autowired
                  private JavaMailSender mailSender;
              
                  @Value("${spring.mail.username}")
                  private String fromEmail;
              
                  @Autowired(required = false)
                  private FreeMawww.devze.comrkerConfigurer freeMarkerConfigurer;
              
                  /**
                   * 发送简单文本邮件
                   */
                  public void sendSimpleMail(String to, String subject, String content) {
                   js   SimpleMailMessage message = new SimpleMailMessage();
                      message.setFrom(fromEmail);
                      message.setTo(to);
                      message.setSubject(subject);
                      message.setText(content);
                      
                      try {
                          mailSender.send(message);
                          log.info("简单邮件发送成功,收件人:{}", to);
                      } catch (Exception e) {
                          log.error("简单邮件发送失败", e);
                          throw new RuntimeException("邮件发送失败", e);
                      }
                  }
              
                  /**
                   * 发送HTML格式邮件
                   */
                  public void sendHtmlMail(String to, String subject, String htmlContent) {
                      MimeMessage message = mailSender.createMimeMessage();
                      
                      try {
                          MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
                          helper.setFrom(fromEmail);
                          helper.setTo(to);
                          helper.setSubject(subject);
                          helper.setText(htmlContent, true);  // true表示是HTML内容
                          
                          mailSender.send(message);
                          log.info("HTML邮件发送成功,收件人:{}", to);
                      } catch (MessagingException e) {
                          log.error("HTML邮件发送失败", e);
                          throw new RuntimeException("HTML邮件发送失败", e);
                      }
                  }
              
                  /**
                   * 发送带附件的邮件
                   */
                  public void sendAttachmentMail(String to, String subject, String content, String filePath) {
                      MimeMessage message = mailSender.createMimeMessage();
                      
                      try {
                          MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
                          helper.setFrom(fromEmail);
                          helper.setTo(to);
                          helper.setSubject(subject);
                          helper.setText(content, false);  // false表示纯文本
                          
                          // 添加附件
                          FileSystemResource file = new FileSystemResource(new File(filePath));
                          String fileName = file.getFilename();
                          helper.addAttachment(fileName, file);
                          
                          mailSender.send(message);
                          log.info("带附件邮件发送成功,收件人:{}", to);
                      } catch (MessagingException e) {
                          log.error("带附件邮件发送失败", e);
                          throw new RuntimeException("带附件邮件发送失败", e);
                      }
                  }
              
                  /**
                   * 发送带内联图片的邮件
                   */
                  public void sendInlineResourceMail(String to, String subject, String content, String filePath, String contentId) {
                      MimeMessage message = mailSender.createMimeMessage();
                      
                      try {
                          MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
                          helper.setFrom(fromEmail);
                          helper.setTo(to);
                          helper.setSubject(subject);
                          helper.setText(content, true);  // HTML内容
                          
                          // 添加内联图片
                          FileSystemResource resource = new FileSystemResource(new File(filePath));
                          helper.addInline(contentId, resource);
                          
                          mailSender.send(message);
                          log.info("带内联图片邮件发送成功,收件人:{}", to);
                      } catch (MessagingException e) {
                          log.error("带内联图片邮件发送失败", e);
                          throw new RuntimeException("带内联图片邮件发送失败", e);
                      }
                  }
              
                  /**
                   * 发送模板邮件
                   */
                  public void sendTemplateMail(String to, String subject, String templateName, Map<String, Object> model) {
                      try {
                          // 使用FreeMarker模板
                          String htmlContent = FreeMarkerfsnUaKiCBYTemplateUtils.processTemplateIntoString(
                                  freeMarkerConfigurer.getConfiguration().getTemplate(templateName),
                                  model);
                          
                          // 发送HTML邮件
                          sendHtmlMail(to, subject, htmlContent);
                      } catch (Exception e) {
                          log.error("模板邮件发送失败", e);
                          throw new RuntimeException("模板邮件发送失败", e);
                      }
                  }
              }
              

              四、创建邮件模板

              如果需要使用FreeMarker模板,在src/main/resources/templates/目录下创建邮件模板:

              1. 注册确认模板(register.html)

              <!DOCTYPE html>
              <html>
              <head>
                  <meta charset="UTF-8">
                  <title>注册确认</title>
                  <style>
                      body { font-family: Arial, sans-serif; line-height: 1.6; }
                      .container { max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #e0e0e0; }
                      .header { background-color: #4CAF50; color: white; padding: 10px; text-align: center; }
                      .content { padding: 20px; }
                      .button { display: inline-block; padding: 10px 20px; background-color: #4CAF50; color: white; text-decoration: none; }
                      .footer { margin-top: 20px; font-size: 12px; color: #666; }
                  </style>
              </head>
              <body>
                  <div class="container">
                      <div class="header">
                          <h2>注册确认邮件</h2>
                      </div>
                      <div class="content">
                          <p>亲爱的 ${username}:</p>
                          <p>欢迎注册我们的系统!请点击下方按钮完成邮箱验证:</p>
                          <p>
                              <a href="${verifyUrl}" rel="external nofollow"  class="button">点击验证邮箱</a>
                          </p>
                          <p>如果您没有注册我们的系统,请忽略此邮件。</p>
                      </div>
                      <div class="footer">
                          <p>此邮件由系统自动发送,请勿回复。</p>
                      </div>
                  </div>
              </body>
              </html>
              

              五、Controller层实现

              创建REST接口用于测试邮件发送:

              import org.springframework.beans.factory.annotation.Autowired;
              import org.springframework.web.bind.annotation.*;
              
              import java.util.HashMap;
              import java.util.Map;
              
              @RestController
              @RequestMapping("/api/mail")
              public class MailController {
              
                  @Autowired
                  private MailService mailService;
              
                  /**
                   * 发送简单文本邮件
                   */
                  @PostMapping("/simple")
                  public String sendSimpleMail(
                          @RequestParam String to,
                          @RequestParam Strijsng subject,
                          @RequestParam String content) {
                      
                      mailService.sendSimpleMail(to, subject, content);
                      return "简单邮件发送成功";
                  }
              
                  /**
                   * 发送HTML邮件
                   */
                  @PostMapping("/html")
                  public String sendHtmlMail(
                          @RequestParam String to,
                          @RequestParam String subject,
                          @RequestParam String htmlContent) {
                      
                      mailService.sendHtmlMail(to, subject, htmlContent);
                      return "HTML邮件发送成功";
                  }
              
                  /**
                   * 发送带附件的邮件
                   */
                  @PostMapping("/attachment")
                  public String sendAttachmentMail(
                          @RequestParam String to,
                          @RequestParam String subject,
                          @RequestParam String content,
                          @RequestParam String filePath) {
                      
                      mailService.sendAttachmentMail(to, subject, content, filePath);
                      return "带附件邮件发送成功";
                  }
              
                  /**
                   * 发送注册确认邮件(使用模板)
                   */
                  @PostMapping("/register")
                  public String sendRegisterMail(
                          @RequestParam String to,
                          @RequestParam String username,
                          @RequestParam String verifyCode) {
                      
                      Map<String, Object> model = new HashMap<>();
                      model.put("username", username);
                      model.put("verifyUrl", "http://yourdomain.com/verify?code=" + verifyCode);
                      
                      mailService.sendTemplateMail(to, "【系统】注册确认邮件", "register.html", model);
                      return "注册确认邮件发送成功";
                  }
              
                  /**
                   * 发送带内联图片的邮件
                   */
                  @PostMapping("/inline")
                  public String sendInlineMail(
                          @RequestParam String to,
                          @RequestParam String subject,
                          @RequestParam String imagePath) {
                      
                      // HTML内容中引用内联图片
                      String htmlContent = "<html><body><h3>这是一封带内联图片的邮件</h3>" +
                                         "<im编程客栈g src='cid:image1'></body></html>";
                      
                      mailService.sendInlineResourceMail(to, subject, htmlContent, imagePath, "image1");
                      return "带内联图片邮件发送成功";
                  }
              }
              

              六、SpringBoot主程序

              import org.springframework.boot.SpringApplication;
              import org.springframework.boot.autoconfigure.SpringBootApplication;
              
              @SpringBootApplication
              public class MailApplication {
              
                  public static void main(String[] args) {
                      SpringApplication.run(MailApplication.class, args);
                  }
              }
              

              七、常见邮件服务器配置

              1. QQ邮箱配置

              spring:
                mail:
                  host: smtp.qq.com
                  port: 587
                  username: your-qq@qq.com
                  password: 你的授权码
                  properties:
                    mail:
                      smtp:
                        auth: true
                        starttls:
                          enable: true
              

              2. 163邮箱配置

              spring:
                mail:
                  host: smtp.163.com
                  port: 465
                  username: your-email@163.com
                  password: 你的授权码
                  properties:
                    mail:
                      smtp:
                        auth: true
                        ssl:
                          enable: true
              

              3. Gmail配置

              spring:
                mail:
                  host: smtp.gmail.com
                  port: 587
                  username: your-email@gmail.com
                  password: 你的授权码(或应用密码)
                  properties:
                    mail:
                      smtp:
                        auth: true
                        starttls:
                          enable: true
              

              八、安全性建议

              授权码管理

              • 不要在配置文件中硬编码真实的授权码
              • 建议使用环境变量或配置中心管理敏感信息
              • 生产环境使用application-prod.yml并从Git中排除

              邮件频率控制

              • 实现发送频率限制,避免被邮件服务器标记为垃圾邮件
              • 考虑使用线程池异步发送邮件,提高性能

              监控与日志

              • 记录所有邮件发送日志,便于排查问题
              • 实现邮件发送失败重试机制

              九、测试示例

              发送简单文本邮件:

              POST /api/mail/simple?to=recipient@example.com&subject=测试邮件&content=这是一封测试邮件
              

              发送注册确认邮件:

              POST /api/mail/register?to=user@example.com&username=张三&verifyCode=123456
              

              发送带附件的邮件:

              POST /api/mail/attachment?to=user@example.com&subject=带附件邮件&content=请查看附件&filePath=/path/to/file.pdf
              

              通过以上配置和代码,您可以在SpringBoot项目中轻松实现各种类型的邮件发送功能,满足用户注册验证、通知提醒、报表发送等业务需求。

              以上就是SpringBoot整合Email发送的完整配置和实现方法的详细内容,更多关于SpringBoot整合Email发送的资料请关注编程客栈(www.devze.com)其它相关文章!

              0

              上一篇:

              下一篇:

              精彩评论

              暂无评论...
              验证码 换一张
              取 消

              最新开发

              开发排行榜