SpringBoot實現郵件發送


首先創建一個郵箱賬號,建議@126.com,@163.com,@qq.com 都可以

開啟smtp,以下是使用圖解:

 

 

 

 

 

 創建SpringBoot項目導入依賴

   <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- 支持發送郵件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

application.properties文件中配置:

spring.mail.default-encoding=UTF-8
spring.mail.host=smtp.163.com
#發送者的郵箱密碼
spring.mail.password=xxxxx
#端口
spring.mail.port=25
#協議
spring.mail.protocol=smtp
#發送者的郵箱賬號
spring.mail.username=xxxxxxx@163.com
server.port=8081

 以文本的形式發送:

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author
 * @site
 * @company
 * @create 2020-03-07 1:06
 */
@RestController
public class MailController {

    @Autowired
    JavaMailSender jsm;

    @Value("${spring.mail.username}")
    private String username;

    @GetMapping("/send")
    public String send(){
        //建立郵箱消息
        SimpleMailMessage message = new SimpleMailMessage();
        //發送者
        message.setFrom(username);
       //接收者
        message.setTo("1352192872@qq.com");
       //發送標題
        message.setSubject("測試");
        //發送內容
        message.setText("測試數據");
        jsm.send(message);
        return "1";
    }
}

 結果:

發送方:

 

 接收方:

 


免責聲明!

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



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