郵件發送
創建一個springboot專案
用IDEA創建springboot專案,

之后可以一直next,依賴之后說,
添加依賴
打開pom.xml,添加如下依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
修改組態檔
打開application.properties,添加如下內容:
// 網易郵箱測驗
spring.mail.username=xxxxxx@163.com
spring.mail.password=網易賬號授權碼
spring.mail.host=smtp.163.com
// 如果是QQ郵箱,則需要加一行,網易郵箱不用
#spring.mail.properties.mail.smtp.ssl.enable=true // 開啟加密驗證
關于授權碼,注意不是你的郵箱密碼,位置如下所示,

只要選擇開啟之后發個短信即可獲取,
測驗類
首先在測驗類要注入JavaMailSenderImpl
@Autowired
private JavaMailSenderImpl mailSender;
運行測驗類進行郵件發送
@Test
void contextLoads() {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setSubject("主題");
simpleMailMessage.setText("內容");
simpleMailMessage.setFrom("xxxxxx@163.com"); // 發件人郵箱
simpleMailMessage.setTo("xxxxxx@163.com"); // 收件人郵箱
mailSender.send(simpleMailMessage);
}
或許你可能一次成功,或許你失敗了,失敗的原因80%都是這個,
org.springframework.mail.MailAuthenticationException: Authentication failed; nested exception is javax.mail.AuthenticationFailedException: 535 Error: xxxxxxx: http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256
說明你的授權碼不對,那就再試試吧,
到這一步,你已經實作了一封由springboot發送的郵件,
實作異步
需要提前添加web依賴,
修改啟動類
添加@EnableAsync注解,開啟異步操作
@EnableAsync // 開啟異步操作
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
創建Controller層和Service層
Service層
創建一個AsyncService類:
package Service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncService {
@Async // Spring看到這個就知道是一個異步操作了
public void async() {
try {
Thread.sleep(10000); // 停止10秒
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("資料正在處理");
}
}
Controller層
創建一個AsyncController類:
頁面訪問,當我們請求服務器時,遇到執行緒方法會停止10秒,
隨便玩玩,不要求獲取方式了,
package Controller;
import Service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@RequestMapping("/async")
public String async() {
asyncService.async();
return "yes";
}
}
添加@Async注解,實作異步操作
package Controller;
import Service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@Async
@RequestMapping("/async")
public String async() {
asyncService.async();
return "yes";
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/261053.html
標籤:java
