1. 程式人生 > >springBoot整合郵件傳送實現

springBoot整合郵件傳送實現

   在不同需求下,郵件的自動傳送還是比較常用的一個功能點,所以自己整理了一個小案例供參考.

1.準備工作(你得首先有個郵箱,同時獲取郵箱的授權碼,以163郵箱為例):

 

2.引入pom依賴:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

3.application.properties配置:

spring.mail.default-encoding=UTF-8
spring.mail.host=smtp.163.com
#傳送者的郵箱授權碼
spring.mail.password=xxxx
#埠
spring.mail.port=25
#協議
spring.mail.protocol=smtp
#傳送者的郵箱賬號
[email protected]

4.前端控制器:

import com.zenithink.demo.utils.MailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping("/email")
public class EmailController {

    @Autowired
    private MailUtil mailUtil;

   

    @Autowired
    JavaMailSender jms;

    @GetMapping("/send")
    @ResponseBody
    public String send(){
        //建立郵件訊息
        SimpleMailMessage mainMessage = new SimpleMailMessage();
        //傳送者
        mainMessage.setFrom("
[email protected]
"); //接收者 mainMessage.setTo("[email protected]"); //傳送的標題 mainMessage.setSubject("測試郵件"); //傳送的內容 mainMessage.setText("成功了"); jms.send(mainMessage); return "1"; }

好了,去試試吧!