SpringBoot发送邮件

Posted 它山之玉

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot发送邮件相关的知识,希望对你有一定的参考价值。

QQ邮箱设置中开启POP3/SMTP服务

  • pom文件

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>
    
  • 配置文件

    ## QQ邮箱配置
    spring:
      mail:
        host: smtp.qq.com #发送邮件服务器
        username: 152****117@qq.com  #发送邮件的邮箱地址
        password:  agq********fb #客户端授权码,不是邮箱密码,这个在qq邮箱设置里面自动生成的
        properties.mail.smtp.port: 465 #端口号465或587
        from: 152****117@qq.com  # 发送邮件的地址,和上面username一致
       #不设置以下属性会报错:Could not connect to SMTP host: smtp.qq.com, port: 465, response: -1
        properties.mail.smtp.starttls.enable: true
        properties.mail.smtp.starttls.required: true
        properties.mail.smtp.ssl.enable: true
        default-encoding: utf-8
    
  • 代码实现

    • 接口代码

      package com.qiankai.qqlogin.util.sendmail;
      
      /**
       * 发送邮件接口
       *
       * @author kai_qian
       * @version v1.0
       * @since 2020/02/25 11:32
       */
      public interface IMailService {
      
          /**
           * 发送文本邮件
           * @param to 收件人
           * @param subject 主题
           * @param content 内容
           */
          void sendSimpleMail(String to, String subject, String content);
      
          /**
           * 发送html邮件
           * @param to 收件人
           * @param subject 主题
           * @param content 内容
           */
          void sendHtmlMail(String to, String subject, String content);
      
          /**
           * 发送带附件的邮件
           * @param to 收件人
           * @param subject 主题
           * @param content 内容
           * @param filePath 附件
           */
          void sendAttachmentsMail(String to, String subject, String content, String filePath);
      }
      
      
    • 业务实现代码

      package com.qiankai.qqlogin.util.sendmail;
      
      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 javax.mail.MessagingException;
      import javax.mail.internet.MimeMessage;
      import java.io.File;
      
      /**
       * 发送邮件的实现类
       *
       * @author kai_qian
       * @version v1.0
       * @since 2020/02/25 11:32
       */
      @Service
      public class IMailServiceImpl implements IMailService {
          private final Logger logger = LoggerFactory.getLogger(this.getClass());
      
          @Autowired
          private JavaMailSender mailSender;
      
          /**
           * 我的QQ邮箱
           */
          @Value("${spring.mail.from}")
          private String from;
      
          @Override
          public void sendSimpleMail(String to, String subject, String content) {
              //创建SimpleMailMessage对象
              SimpleMailMessage message = new SimpleMailMessage();
              //邮件发送人
              message.setFrom(from);
              //邮件接收人
              message.setTo(to);
              //邮件主题
              message.setSubject(subject);
              //邮件内容
              message.setText(content);
              //发送邮件
              mailSender.send(message);
          }
      
          @Override
          public void sendHtmlMail(String to, String subject, String content) {
              //获取MimeMessage对象
              MimeMessage message = mailSender.createMimeMessage();
              MimeMessageHelper messageHelper;
              try {
                  messageHelper = new MimeMessageHelper(message, true);
                  //邮件发送人
                  messageHelper.setFrom(from);
                  //邮件接收人
                  messageHelper.setTo(subject);
                  //邮件主题
                  message.setSubject(subject);
                  //邮件内容,html格式
                  messageHelper.setText(content, true);
                  //发送
                  mailSender.send(message);
                  //日志信息
                  logger.info("邮件已经发送。");
              } catch (MessagingException e) {
                  logger.error("发送邮件时发生异常!", e);
              }
          }
      
          @Override
          public void sendAttachmentsMail(String to, String subject, String content, String filePath) {
              MimeMessage message = mailSender.createMimeMessage();
              try {
                  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 = filePath.substring(filePath.lastIndexOf(File.separator));
                  helper.addAttachment(fileName, file);
                  mailSender.send(message);
                  //日志信息
                  logger.info("邮件已经发送。");
              } catch (MessagingException e) {
                  logger.error("发送邮件时发生异常!", e);
              }
          }
      }
      
      
    • 直接调用方法即可

    @RestController
    

@RequestMapping("/mail")
public class EmailController {
/** 邮件接收者 */
private static final String TEST_RECEIVER = "xxxxxxx@qq.com";

@Autowired
private IMailService mailService;

@GetMapping("/simple")
public String sendSimpleMail() {
    mailService.sendSimpleMail(TEST_RECEIVER, "你好,普通邮件","内容:第一封邮件");
    return "simple-ok";
}

@GetMapping("/html")
public String sendHTMLMail() {
    mailService.sendSimpleMail(TEST_RECEIVER,"主题:你好html邮件","<h1>内容:</h1><p>第一封html邮件<p>");
    return "html-ok";
}

}
```

参考博客
https://www.jianshu.com/p/a7097a21b42d
https://www.cnblogs.com/eatandsleep/p/12205573.html

以上是关于SpringBoot发送邮件的主要内容,如果未能解决你的问题,请参考以下文章

25springboot发送邮件

25springboot发送邮件

补习系列(12)-springboot 与邮件发送

使用SpringBoot发送mail邮件

java springboot+maven发送邮件

SpringBoot定时发送邮件