Springboot integrates timers to send emails regularly

1. Create a springboot project:

To write a timer, you can see: springboot implements timer

Write mail service class: you can see: springboot send mail (1): send simple mail

2. Start the class to enable timing:

/**
 * Startup class
 */
 @SpringBootApplication
 //Enable timing
 @EnableScheduling
 public class Application {

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

}

3. Main business code:

/**
 * Scheduled task class, to achieve scheduled email sending
 * Created by ASUS on 2018/5/6
 *
 * @Authod Grey Wolf
 */
 //To be declared as a bean, the timing effect cannot be achieved without declaring the startup class to start
 @Component
 public class SchedulerTask {

    @Autowired
 private MailService mailService ;
 @Value ( "${mail.fromMail.addr}" )
     private String form ;
     private int count = 1 ;
 /**
      * means send mail every 6 seconds
      */
 @Scheduled ( cron = " */6 * * * * ?" )
     private void processes (){    
    

        
        String content= "springboot integrates timers to send regular emails, this is the first" +( count ++)+ "mail" ;
 mailService .sendMail( form , "simple mail" , content) ;
 System. out .println( " Sending scheduled mail successfully" ) ;
 }                    
}

Mail service class:

/**
 *
 * 邮件服务类
 * Created by ASUS on 2018/5/5
 *
 * @Authod Grey Wolf
 */
@Service("mailService")
public class MailServiceImpl implements MailService {


    @Autowired
 private JavaMailSender mailSender ;
 @Value ( "${ mail.fromMail.addr }" )
     private String form ;
 /**
      * Send simple mail
      * @param to recipient
      * @param subject      * @param content
 *
      /
 @ Override
 public void sendMail (String to , String subject , String content) {    
                
        SimpleMailMessage mailMessage=new SimpleMailMessage();
        mailMessage.setFrom(form);
        mailMessage.setTo(to);
        mailMessage.setSubject(subject);
        mailMessage.setText(content);
        try {
            mailSender.send(mailMessage);
//            System.out.println("发送简单邮件");
        }catch (Exception e){
            e.printStackTrace() ;
 System.out             .println ( "Failed to send simple mail" ) ;
 }        
    }



}

4.run start the class application.class, test the effect:


Note: There may be reasons why the email may fail to be sent: the email is sent too frequently, the network is abnormal, etc.



My motto: No, I can learn; I fall behind, I can catch up; I fall, I can stand up; I will do it.



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325725380&siteId=291194637