springboot定时发送邮件

首先创建一个maven项目,pom配置如下:

	<parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-parentartifactId>
        <version>2.1.5.RELEASEversion>
    parent>
    <dependencies>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-webartifactId>
    dependency>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-mailartifactId>
      dependency>
    dependencies>

接下来新建一个application.yml配置邮箱设置

spring:
  mail:
    username: [email protected]
    password: xxx //注意这里是开通pop3/smtp后给的安全密码,并不是邮箱密码
    host: smtp.163.com //qq的话就是smtp.qq.com
@Controller
@RequestMapping("mail")
public class MailController {
    @Autowired
    JavaMailSenderImpl mailSender;
    //发送普通邮箱
    @RequestMapping("send")
    public void send()
    {
        SimpleMailMessage mailMessage=new SimpleMailMessage();
        mailMessage.setSubject("springboot邮件测试");
        mailMessage.setText("四月是你的谎言");
        mailMessage.setFrom("[email protected]");//发送者,本人邮箱
        mailMessage.setTo("[email protected]");//发送给他人邮箱
        mailSender.send(mailMessage);
    }
    //发送邮箱带附件
    @RequestMapping("sendadvance")
    public void sendadvance() throws MessagingException {
        MimeMessage mimeMessage=mailSender.createMimeMessage();
        MimeMessageHelper helpers = new MimeMessageHelper(mimeMessage,true);
        helpers.setSubject("springboot mail advance");
        helpers.setText("

四月是你的宫园薰

"
,true); helpers.addAttachment("1.jpg",new File("F:\\360downloads\\311661.jpg"));//附件在本地位置 helpers.setTo("[email protected]");//发送给他人邮箱 helpers.setFrom("[email protected]");//发送者,本人邮箱 mailSender.send(mimeMessage); }

测试效果:
访问http://localhost:8080/mail/sendadvance
springboot定时发送邮件_第1张图片
接下来看看springboot自带的定时任务,相比spring整合quarz,这个简单多了。
需要在启动类中加入以下注解和在方法上加入注解@Scheduled(cron = “0 30 11 * * ?”)//这是cron表达式,可以百度更加了解

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

最后将定时任务和发邮件整合起来
创建一个service

@Service
public class ScheduledMailService {
    @Autowired
    JavaMailSenderImpl mailSender;
    @Scheduled(cron = "0 30 11 * * ?")//cron表达式我这里表示每天的11.30触发,当服务启动后会自动执行方法
    public void send()//上面的send方法
    {
        //System.out.println("send");
        SimpleMailMessage mailMessage=new SimpleMailMessage();
        mailMessage.setSubject("我在校园打卡");
        mailMessage.setText("打卡了 from by 友人A");
        mailMessage.setFrom("[email protected]");
        mailMessage.setTo("[email protected]");
        mailSender.send(mailMessage);
    }
}

效果:
springboot定时发送邮件_第2张图片

你可能感兴趣的:(java,web学习)