SpringBoot发送邮件、执行异步任务、定时任务

本文介绍了如何使用SpringBoot进行邮件发送,包括简单邮件和带有HTML内容及附件的复杂邮件的发送。同时,展示了如何设置异步任务和定时任务,异步任务通过@Async注解实现,定时任务则通过@EnableScheduling和@Scheduled注解配合cron表达式来设定执行计划。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


使用SpringBoot操作邮箱,我们先需要导入邮箱依赖

发送邮件

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

发送邮箱之前,我们需要先在application.yml配置文件编写邮箱相关配置

#邮箱密码,qq邮箱为例,需要前往qq邮箱生成获取。(并不是邮箱登录密码)
spring.mail.password=xxxxxxxxxxxxx
#邮箱用户名
spring.mail.username=xxxxxxx@qq.com
#邮箱类型
spring.mail.host=smtp.qq.com
#开启邮箱文件配置
spring.mail.properties.mail.smtp.ssl.enable=true
#服务启动端口
server.port=8082		

发送邮箱的方法体

		//一个简单的邮件
		SimpleMailMessage message = new SimpleMailMessage();
		message.setSubject("标题");
		message.setFrom("xxxxxxx.qq.com");		//邮箱来自谁
		message.setTo("xxxxxxx.qq.com");		//邮箱发送地址
		message.setText("你好啊,通过java发送的邮件");

		javaMailSender.send(message);

发送html片段。并附带附件

//一个复杂的邮件
		MimeMessage mimeMessage = javaMailSender.createMimeMessage();

		//组装
		MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");

		helper.setSubject("这是java邮件测试");
		helper.setText("<p style='color:red'>如果你收到了,就代表测试成功</p><br><h3>html测试页面</h3>",true);		//true表示发送的文本为html。浏览器会解析
		helper.setTo("xxxxxxx@qq.com");
		helper.setFrom("xxxxxxx@qq.com");

		//附件
		helper.addAttachment("1.jpg", new File("C:\\Users\\Hasee\\Desktop\\1.jpg"));



		javaMailSender.send(mimeMessage);

异步任务

1、启动类开启异步功能,使用注解@EnableAsync
2、方法体上面加上注解@Async,表示当前方法可以异步执行

	@Async
	public void hello()
	{
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("数据正在处理");
	}

定时任务

1、启动类开启定时任务功能。使用注解@EnableScheduling
2、将定时执行任务的所在类使用@Component注入到Spring容器
3、编写定时执行的方法,在该方法上加上注解@Scheduled(cron = “0 * * * * ?”)

cron是时间表达式。通过cron确定执行时间

实例

@Service
public class TestScheduler {

	@Scheduled(cron = "0 * * * * ?")
	public void hello(){
		System.out.println("你好啊,你被定时执行了");
	}
}

启动类

@EnableAsync        //开启异步功能
@EnableScheduling       //开启定时功能
@SpringBootApplication
public class AsyncApplication {

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

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

languageStudents

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

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

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

打赏作者

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

抵扣说明:

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

余额充值