Spring Boot demo系列(七):郵件服務

1 概述

Spring Boot整合郵件服務,包括髮送普通的文本郵件以及帶附件的郵件。java

2 郵箱選擇

這裏選擇的是QQ郵箱做爲發送的郵箱,固然也能夠選擇其餘的郵箱,只是具體的配置不同。ios

使用QQ郵箱的話,須要在我的設置中開啓SMTP服務:git

在這裏插入圖片描述

在這裏插入圖片描述

發送短信後完成驗證便可,會有一個受權碼,先複製下來保存。github

3 具體實現

3.1 依賴

提供了starter算法

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

gradlespring

implementation 'org.springframework.boot:spring-boot-starter-mail'

3.2 郵件接口

只有兩個簡單的接口,一個是發送純文本的,一個是發送帶附件的:安全

public interface MailService {
    void sendSimpleMail(String to,String subject,String content);
    void sendAttachmentMail(String to, String subject, String content, Path file) throws MessagingException;
}

3.3 接口實現

@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class MailServiceImpl implements MailService{
    private final JavaMailSender sender;

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

    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        sender.send(message);
    }

    @Override
    public void sendAttachmentMail(String to, String subject, String content, Path file) throws MessagingException {
        MimeMessage message = sender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message,true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content);
        helper.addAttachment(file.getFileName().toString(),new FileSystemResource(file));
        sender.send(message);
    }
}

JavaMailSenderSpring Boot攜帶的郵件發送接口,注入後能夠發送SimpleMailMessage以及MimeMessage類型的信息。bash

  • SimpleMailMessage:簡單的郵件信息對象,封裝了一些常見的屬性,好比寄信地址以及收信地址,發送日期,主題,內容等
  • MimeMessage:發送MIME類型的郵件信息,MIME指的是Multipurpose Internet Mail Extensiosns,是描述消息內容類型的因特網標準,能包含文本,圖像,音頻,視頻以及其餘應用程序專用的數據
  • MimeMessageHelper:用於設置MimeMessage屬性的類,能夠利用其中的addAttachment添加附件
  • setFrom/setTo/setSubject/setText:分別表示設置寄信地址/收信地址/主題/內容

3.4 測試類

@SpringBootTest
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
class DemoApplicationTests {
    private final MailService service;

    @Test
    void contextLoads() throws URISyntaxException, MessagingException {
        service.sendSimpleMail("xxx@xxx.com","這是主題","這是內容");
        service.sendAttachmentMail("xxxx@xx.com","這是主題","這是內容", Path.of(Objects.requireNonNull(getClass().getClassLoader().getResource("pic/1.jpg")).toURI()));
        //附件爲resources下pic/1.jpg
        service.sendAttachmentMail("xxxx@xxx.com","這是主題","這是內容", Path.of("/","srv","http","1.jpg"));
        //附件爲/srv/http/1.jpg
    }

發送文本直接指定主題和內容便可,發送帶附件的話:服務器

  • 若是是resources下的內容,使用getClass().getClassLoader().getReource("xxx/xxx")
  • 若是是絕對路徑,使用Path.of("/","path1","path2",...,"filename")

3.5 配置文件

spring:
  mail:
    host: smtp.qq.com
    username: xxxxxxx@qq.com
    password: xxxxxxxxxx
    port: 465
    properties:
      mail:
        smtp:
          ssl:
            enable: true
          auth: true
          starttls:
            enable: true
            required: true

做爲Demo使用只須要修改username以及password便可。ide

  • username:發送的用戶郵箱
  • password:不是郵箱密碼,而是受權碼,就是剛纔開啓SMTP服務出現的受權碼

其餘配置說明:

  • hostSMTP服務器地址
  • port:端口,能夠選擇465/587host以及port能夠參考QQ郵箱文檔
  • properties:裏面都是一些安全設置,開啓SSL以及認證等

3.6 測試

修改測試類的郵箱,運行單元測試便可。

在這裏插入圖片描述

若是沒經過,能夠參考這裏,羅列了常見的錯誤碼以及可能的解決方案。

4 加密

因爲用戶名以及密碼都直接寫在了配置文件中,若是泄露的話會很危險,所以須要對配置文件進行加密。

具體的話能夠參考筆者以前的原力計劃文章,戳這裏

4.1 依賴

<dependency>
    <groupId>com.github.ulisesbocchio</groupId>
    <artifactId>jasypt-spring-boot-starter</artifactId>
    <version>3.0.3</version>
</dependency>

gradle

implementation("com.github.ulisesbocchio:jasypt-spring-boot-starter:3.0.3")

4.2 配置文件

配置文件只須要加上加密口令便可:

jasypt:
  encryptor:
    password: test

默認使用的是PBE加密算法,PBE實際上是一種組合加密算法,默認是採用HCMA算法(混合CMA-ES算法)+SHA512消息摘要算法+AES256對稱加密算法。

另外,若是不想在配置文件直接寫上加密的口令,可使用如下三種方法對口令進行參數化:

命令行參數(運行時設置):

java -jar xxx.jar --jasypt.encryptor.password=test

應用環境變量(運行時設置):

java -Djasypt.encryptor.password=test -jar xxx.jar

系統環境變量(在配置文件中設置):

jasypt:
  encryptor:
    password: ${TEST}
# 表示獲取環境變量TEST的值做爲加密口令

4.3 測試類

新建一個測試類:

@SpringBootTest
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class EncryptAndDecrypt {
    private final StringEncryptor encryptor;
    @Value("${spring.mail.username}")
    private String username;
    @Value("${spring.mail.password}")
    private String password;

    @Test
    public void encrypt()
    {
        System.out.println(encryptor.encrypt(username));
        System.out.println(encryptor.encrypt(password));
    }

    @Test
    public void decrypt()
    {
        System.out.println(username);
        System.out.println(password);
    }
}

4.4 獲取密文

假設明文以下:

在這裏插入圖片描述

運行encrypt便可,輸出以下:

在這裏插入圖片描述

4.5 替換明文

加上前綴ENC(以及後綴)去替換明文:

在這裏插入圖片描述

4.6 測試

獲取明文直接運行decrypt便可,輸出:

在這裏插入圖片描述

這樣就完成加密了。

5 源碼

Java版:

Kotlin版:

相關文章
相關標籤/搜索