Spring Boot定时异步邮件发送

一、版本

Spring Boot 2.2.2RELEASE

二、依赖

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

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

三、主启动类

加上开启定时任务和异步的注解

@EnableScheduling
@EnableAsync

四、邮件

登录QQ邮箱,设置->账户,开启smtp服务

保存好自己的授权码

五、配置 

配置文件

# 服务端口
server.port=8089
# 服务名称
spring.application.name=testEmail
# 访问前缀
server.servlet.context-path=/
all.cron=0 2 0-9 * * ?
# 邮件配置
spring.mail.username=(自己的邮箱xxx@qq.com)
spring.mail.password=(自己的授权码)
spring.mail.host=smtp.qq.com
spring.mail.properties.mail.smtp.ssl.enable=true
# 日志文件
logging.file.name=${spring.application.name}${server.port}.log

六、代码

SendEmail.java

package test.email.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;

@Service
public class SendEmail {

	@Value("${spring.mail.username}")
	private String fromEmail;

	@Autowired
	private JavaMailSenderImpl javaMailSender;

	public void sendEmail(String email) {
		SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
		simpleMailMessage.setSubject("提示!");
		simpleMailMessage.setText("内容!");
		simpleMailMessage.setFrom(fromEmail);
		simpleMailMessage.setTo(email);
		javaMailSender.send(simpleMailMessage);
	}
}

TestTask.java

package test.email.task;

import test.email.service.SendEmail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class TestTask {

	@Autowired
	private SendEmail sendEmail;

	// 发送邮件
	@Async
	@Scheduled(cron = "${all.cron}")
	public void caoWeiReport() {
		sendEmail.sendEmail("发送给谁的邮箱");
	}

}

 七、结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值