SpringMail邮件发送

Spring Email抽象的核心是MailSender接口,MailSender的实现能够将想要发送的邮件通过邮件服务器发送到用户邮箱,实现发送邮箱的功能

image-20230117192531271

1.起步依赖

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>
​
<!-- mail -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
​
<!-- knife4j,测试接口 -->
<dependency>
   <groupId>com.github.xiaoymin</groupId>
   <artifactId>knife4j-spring-boot-starter</artifactId>
   <version>3.0.3</version>
</dependency>

2.相关配置

2.1 授权码获取

image-20230117193002250

2.2 yaml配置文件

spring:
    mvc:
      path match:
        matching-strategy: ant_path_matcher

    mail:
       # 配置 SMTP 服务器地址
      host: smtp.qq.com
       # 发送者邮箱
      username: junn127@qq.com
       # 配置授权码
      password: ********
       # 端口号465或587
      port: 587
       # 默认的邮件编码为UTF-8
      default-encoding: UTF-8
       # 配置SSL 加密工厂
      properties:
        mail:
          smtp:
            socketFactoryClass: javax.net.ssl.SSLSocketFactory
          debug: true

2.3 mail配置文件

@Component
public class EmailConfig {
​
   @Value("${spring.mail.username}")
   private String  emailForm;
​
   public String getEmailForm() {
       return emailForm;
  }
​
   public void setEmailForm(String emailForm) {
       this.emailForm = emailForm;
  }
}

2.4 Swagger配置文件

@Configuration
@EnableOpenApi
public class SwaggerConfig {
​
   @Bean
   public Docket desertsApi1() {
       return new Docket(DocumentationType.OAS_30)
          .apiInfo(apiInfo("MAIL——Swagger3.0", "1.0"))
          .select()
          .apis(RequestHandlerSelectors.basePackage("com.mail.controller"))
          .paths(PathSelectors.any())
          .build()
          .groupName("邮件发送")
          .enable(true);
  }
​
​
   private ApiInfo apiInfo(String title, String version) {
       return new ApiInfoBuilder()
          .title(title)
          .description("XX项目接口测试页面")
          .contact(new Contact("墨初", "https://mochu.co", "junn127@qq.com"))
          .termsOfServiceUrl("")
          .version(version)
          .build();
  }
}

3.具体实现

@Service
public class EmailServiceImpl implements EmailService {
​
   @Autowired
   private EmailConfig emailConfig;
​
   @Autowired
   private JavaMailSender mailSender;
​
​
   /**
    * 简单邮件的发送
    *
    * @param sendTo
    * @param title
    * @param content
    */
   @Override
   public void sendMailSimpleMail(String sendTo, String title, String content) {
       SimpleMailMessage message = new SimpleMailMessage();
       message.setFrom(emailConfig.getEmailForm());
       message.setTo(sendTo);
       message.setSubject(title);
       message.setText(content);
       mailSender.send(message);
  }
​
   /**
    * 发送一个带html格式的邮件
    *
    * @param sendTo
    * @param title
    * @param content
    */
   @Override
   public void sendHtmlMail(String sendTo, String title, String content) {
       MimeMessage mimeMailMessage = null;
       try {
           mimeMailMessage = mailSender.createMimeMessage();
           MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true);
           mimeMessageHelper.setFrom(emailConfig.getEmailForm());
           mimeMessageHelper.setTo(sendTo);
           mimeMessageHelper.setSubject(title);
           StringBuilder sb = new StringBuilder();
           sb.append("<h1>SpirngBoot测试邮件HTML</h1>")
              .append("\"<p style='color:#F00'>" + content + "</p>")
              .append("<p style='text-align:right'>右对齐</p>");
           mimeMessageHelper.setText(sb.toString(), true);
           mailSender.send(mimeMailMessage);
      } catch (Exception e) {
           e.printStackTrace();
      }
  }
​
   /**
    * 发送带附件格式的邮件
    *
    * @param sendTo
    * @param title
    * @param content
    */
   @Override
   public void sendAttachmentMail(String sendTo, String title, String content) {
       MimeMessage mimeMailMessage = null;
       try {
           mimeMailMessage = mailSender.createMimeMessage();
           MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true);
           mimeMessageHelper.setFrom(emailConfig.getEmailForm());
           mimeMessageHelper.setTo(sendTo);
           mimeMessageHelper.setSubject(title);
           mimeMessageHelper.setText(content);
           FileSystemResource file = new FileSystemResource(new File("文件路径"));
           mimeMessageHelper.addAttachment("mail.png", file);
​
           mailSender.send(mimeMailMessage);
      } catch (Exception e) {
           e.printStackTrace();
      }
  }
}

4.测试

@Controller
public class EmailController {
​
   @Autowired
   private EmailService emailService;
​
   @PostMapping("/simple")
   @ResponseBody
   public String sendSimpleEmail(String sendTo) {
       emailService.sendMailSimpleMail(sendTo, "发送简单邮件", "你好");
       return "success";
  }
​
   @PostMapping("/sendHtmlMail")
   @ResponseBody
   public String sendHtmlMail(String sendTo) {
       emailService.sendHtmlMail(sendTo, "发送一个带html格式的邮件", "这是一封带html格式的邮件");
       return "success";
  }
​
   @PostMapping("/sendAttachMail")
   @ResponseBody
   public String sendAttachMail(String sendTo) {
       emailService.sendAttachmentMail(sendTo, "发送带附件格式的邮件", "这是一封发送带附件格式的邮件");
       return "success";
  }
}

测试地址:/doc.html

© 版权声明
THE END
喜欢就支持一下吧
点赞0
分享
评论 抢沙发
墨初的头像-墨初小屋

昵称

取消
昵称表情代码图片