本文來自于千鋒教育在阿裡雲開發者社群學習中心上線課程《SpringBoot實戰教程》,主講人楊紅豔,
點選檢視視訊内容。
SpringBoot整合Email
添加依賴:
<!-- 郵件依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
建立全局配置檔案:application.properties
# JavaMailSender 郵件發送的配置
spring.mail.host=smtp.qq.com #smtp.163.com
[email protected]
spring.mail.password=cjmegwewmbiqcach #授權碼
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
#若使用QQ郵箱發送郵件,則需要修改為spring.mail.host=smtp.qq.com,同時spring.mail.password改為QQ郵箱的授權碼。
#QQ郵箱->設定->賬戶->POP3/SMTP服務:開啟服務後會獲得QQ的授權碼
出現認證失敗的解決方案:因為JDK1.8中jrelibsecurity中兩個 jar 包替換的緣故。将下載下傳後的local_policy.jar和US_export_policy.jar替換到JDK1.8的jrelibsecurity檔案夾即可。
建立包:com.qianfeng.email
擷取發件人的郵箱:
@Component
public class EmailConfig {
@Value("${spring.mail.username}")
private String emailFrom;
public String getEmailFrom() {
return emailFrom;
}
public void setEmailFrom(String emailFrom) {
this.emailFrom = emailFrom;
}
}
EmailService:
public interface EmailService {
//發送簡單的郵件
void sendSimpleMail(String sendTo, String title, String content);
}
EmailServiceImpl:
@Service
public class EmailServiceImpl implements EmailService {
@Autowired
private EmailConfig emailConfig;
@Autowired
private JavaMailSender mailSender;
@Override
public void sendSimpleMail(String sendTo, String title, String content) {
//簡單郵件的發送
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(emailConfig.getEmailFrom());
message.setTo(sendTo);
message.setSubject(title);
message.setText(content);
mailSender.send(message);
}
}
EmailController:
@Controller
public class EmailController {
@Autowired
private EmailService emailService;
@RequestMapping("/simple")
@ResponseBody
public String sendSimpleEmail() {
emailService.sendSimpleMail("[email protected]", "你好", "明天去你家玩兒");
return "success";
}
}
在啟動類中添加所有需要掃描的包:
@SpringBootApplication(scanBasePackages="com.qianfeng.email")
執行結果:
