pom.xml
<!--郵件javax.mail--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
MyController.class
@Controller public class MyController { @Autowired AsyncService asyncService; @ResponseBody @GetMapping("/hello") public String hello(){ asyncService.hello(); return "你好"; } }
AsyncService.class
@Service public class AsyncService { @Async public void hello(){ try { Thread.sleep(3000); } catch (Exception e) { e.printStackTrace(); } System.out.println("數據正在處理。。。。。。"); } }
SpringbootTaskApplication.class
@EnableAsync //開啟異步注解功能 @SpringBootApplication public class SpringbootTaskApplication { public static void main(String[] args) { SpringApplication.run(SpringbootTaskApplication.class, args); } }
application.properties
spring.mail.username=110xxxxx@qq.com
#授權碼
spring.mail.password=xxxxxxxxxxxxx
spring.mail.host=smtp.qq.com
#開啟加密驗證
spring.mail.properties.mail.smtp.ssl.enable=true
SpringbootTaskApplicationTest.class
@SpringBootTest
class SpringbootTaskApplicationTests {
@Autowired
JavaMailSenderImpl mailSender;
@Test
void contextLoads() {
SimpleMailMessage message=new SimpleMailMessage();
message.setSubject("xx你好啊");
message.setText("java這條路行下去");
message.setTo("110xxxxx6@qq.com");
message.setFrom("110xxxxx56@qq.com");
mailSender.send(message);
}
}