SpringBoot发送邮件定时任务


一、定时任务启动注解

@SpringBootApplication
@EnableScheduling   //定时任务的注解
public class DemoApplication {

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

}

二、pom依赖

        <!-- mail邮件服务启动器 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

三、application-mail.properties

#QQ\u90AE\u7BB1\u90AE\u4EF6\u53D1\u9001\u670D\u52A1\u914D\u7F6E
spring.mail.host=smtp.qq.com
spring.mail.port=587

## qq邮箱
spring.mail.username=1311328238@qq.com
## 这里填邮箱的授权码
spring.mail.password=asdasdasdasd

四、工具类MailUtils

@Component
public class MailUtils {
    @Autowired
    private JavaMailSenderImpl mailSender;
    
    @Value("${spring.mail.username}")
    private String mailfrom;

    // 发送简单邮件
    public void sendSimpleEmail(String mailto, String title, String content) {
        //  定制邮件发送内容
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(mailfrom);
        message.setTo(mailto);
        message.setSubject(title);
        message.setText(content);
        // 发送邮件
        mailSender.send(message);
    }
}

五、测试

@Component
class DemoApplicationTests {

    @Autowired
    private MailUtils mailUtils;

    /**
     * 定时邮件发送任务,每月1日中午12点整发送邮件
     */
    @Scheduled(cron = "0 0 12 1 * ?")
    void sb(){
        //  定制邮件内容
        StringBuffer content = new StringBuffer();
        content.append("HelloWorld");
        //分别是接收者邮箱,标题,内容
        mailUtils.sendSimpleEmail("123456789@qq.com","自定义标题",content.toString());
    }
    
}

其他

cron表达式格式:
其中 {秒数} {分钟} {小时} {日期} {月份} {星期} {年份(可为空)}
详细链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

和烨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值