Java教程

springBoot 定时+发送邮件

本文主要是介绍springBoot 定时+发送邮件,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

定时任务引入meaven依赖

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency>

邮件服务引入依赖

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>

1.定时任务

  1. 在springBoot启动类加上@EnableScheduling

@SpringBootApplication
@EnableScheduling

public class Application{
  public static void main(String[] args) {
	SpringApplication.run(Application.class, args);
}

}

  • demo1
    @Component

    public class SchedulerTask {
    
      private int count=0;
    
      @Scheduled(cron="*/6 * * * * ?")
      private void process(){
        System.out.println("this is scheduler task runing  "+(count++));
    }
    

}

  • demo2
    @Component

    public class Scheduler2Task {
    
      private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    
      @Scheduled(fixedRate = 6000)
      public void reportCurrentTime() {
          System.out.println("现在时间:" + dateFormat.format(new Date()));
      }
    

    }

2.邮件服务

  1. 在application.properties中添加邮箱配置

spring.mail.host=smtp.qq.com //邮箱服务器地址
spring.mail.username=xxx@qq.com //用户名
spring.mail.password=xxyyooo //开启POP3/SMTP服务的验证码 ,具体类型邮件服务详情度娘
spring.mail.default-encoding=UTF-8
mail.fromMail.addr=xxx@oo.com //发送邮件本人

  1. 编写接口
    public interface MailService { void sendSimpleMail(String to,String subject,String content); }
    3.编写实现类
    @Component
public class MailServiceImpl implements MailService{

  private final Logger logger = LoggerFactory.getLogger(this.getClass());

  @Autowired
  private JavaMailSender mailSender;

  @Value("${mail.fromMail.addr}")
  private String from;

  @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);
      }

  }

}
4.编写测试类进行测试

@SpringBootTest

public class MailServiceTest {

  @Autowired
  private MailService MailService;

  @Test
  public void testSimpleMail() throws Exception {
      MailService.sendSimpleMail("***@qq.com","test simple mail"," hello this is simple mail");
  }

}

这篇关于springBoot 定时+发送邮件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!