使用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);
}
}