1. 程式人生 > 程式設計 >spring boot發簡單文字郵件案例

spring boot發簡單文字郵件案例

首先要去郵箱開啟POP3/SMTP許可權:

然後會提供個授權碼,用來發送郵件。忘記了,可以點生成授權碼再次生成。

1、引入spring boot自帶的mail依賴,這裡版本用的:<spring-boot.version>1.4.3.RELEASE</spring-boot.version>

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-mail</artifactId>
  <version>${spring-boot.version}</version>
  <scope>provided</scope>
</dependency>

2、spring boot配置檔案新增郵箱引數資訊

spring.mail.host=smtp.qq.com
spring.mail.username=你的qq號碼@qq.com
spring.mail.password=qq郵箱開啟SMTP提供的授權碼(注意:不是你的qq郵箱密碼)#下面一般不用動
spring.mail.default-encoding=${spring.http.encoding.charset}
spring.mail.properties.mail.smtp.connectiontimeout=5000 
spring.mail.properties.mail.smtp.timeout=3000
spring.mail.properties.mail.smtp.writetimeout=5000
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

3、測試傳送

@Autowired
        private JavaMailSender mailSender;
        
        @Value("${spring.mail.username}")
        private String from;


SimpleMailMessage smm = new SimpleMailMessage();
            smm.setFrom(from);
            smm.setTo("傳送方郵件地址");
            smm.setSubject("springboot測試郵件");
            smm.setText("簡單文字郵件測試傳送!");
            mailSender.send(smm);

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。