springboot下實現郵件發送功能


springboot給我們封裝好了郵件功能,非常簡單,只需要稍微配置下就ok。

引入jar

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
View Code
MailService.java
@Service
public class MailService {

     @Autowired
     private JavaMailSender mailSender; //框架自帶的
    
     @Value("${spring.mail.username}")  //發送人的郵箱  比如155156641XX@163.com
  private String from;
   
     @Async  //意思是異步調用這個方法
  public void sendMail(String title, String url, String email) {
    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom(from); // 發送人的郵箱
    message.setSubject(title); //標題
    message.setTo(email); //發給誰  對方郵箱
    message.setText(url); //內容
    mailSender.send(message); //發送
  } 

}

還需要在配置文件yml中寫    下面的配置

spring.mail.host: smtp.163.com
spring.mail.username: 155156641xx@163.com
spring.mail.password: 填上你自己的
spring.mail.properties.mail.smtp.auth: true
spring.mail.properties.mail.smtp.starttls.enable: true
spring.mail.properties.mail.smtp.starttls.required: true

就ok了




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM