SpringBoot11 讀取properties文件、發送郵件


 

1 讀取properties文件

  1.1 ResourceBundle

    幫助我們事先國際化

    1.1.1 前提

      properties文件的命名方式必須體現除語言和國別

      例如:test_zh_CN.propertis -> 表示名稱為test,語言為中文,國別為中國的properties文件

  1.2 Locale  

    根據語言和地區構造一個語言環境

    例如:Locale locale = new Locale("zh", "CN"); -> 構造了一個語言為中文,地區為中國的語言環境

  1.3 讀取properties文件

    1.3.1 在springboot項目的resource目錄下創建properties文件

      

xiangxu.name=WYS
xiangxu.address=yuzu
test_zh_CN.properties

    1.3.2 利用ResourceBundle讀取配置文件中的內容

ResourceBundle resourceBundle = ResourceBundle.getBundle("test", new Locale("zh", "CN"));

      代碼解釋:ResourceBundle對象就代表了需要讀取的那個配置文件

      技巧01:如果找不到test_zh_CN.properties就會去找test_zh_CN.properties,如果也找不到就會去找test.properties,如果還是找不到就會拋出異常

String name = resourceBundle.getString("xiangxu.address");

      代碼解釋:利用ResourceBundle對象的getString方法去獲取相應的值

/**
     * Gets a string for the given key from this resource bundle or one of its parents.
     * Calling this method is equivalent to calling
     * <blockquote>
     * <code>(String) {@link #getObject(java.lang.String) getObject}(key)</code>.
     * </blockquote>
     *
     * @param key the key for the desired string
     * @exception NullPointerException if <code>key</code> is <code>null</code>
     * @exception MissingResourceException if no object for the given key can be found
     * @exception ClassCastException if the object found for the given key is not a string
     * @return the string for the given key
     */
    public final String getString(String key) {
        return (String) getObject(key);
    }
getString源碼

  1.4 編寫讀取Properties文件的工具類

package cn.xiangxu.springboottest.utils;

import java.util.Enumeration;
import java.util.Locale;
import java.util.ResourceBundle;

/**
 * 讀取properties文件工具類
 * 讀取發送郵件所需信息的properties文件的工具類
 */
public class PropertiesUtil {
    private final ResourceBundle resource;
    private final String fileName;

    /**
     * 構造函數實例化部分對象,獲取文件資源對象
     *
     * @param fileName
     */
    public PropertiesUtil(String fileName)
    {
        this.fileName = fileName;
        Locale locale = new Locale("zh", "CN");
        this.resource = ResourceBundle.getBundle(this.fileName, locale);
    }

    /**
     * 根據傳入的key獲取對象的值 2016年12月17日 上午10:19:55 getValue
     *
     * @param key properties文件對應的key
     * @return String 解析后的對應key的值
     */
    public String getValue(String key)
    {
        String message = this.resource.getString(key);
        return message;
    }

    /**
     * 獲取properties文件內的所有key值<br>
     * 2016年12月17日 上午10:21:20 getKeys
     *
     * @return
     */
    public Enumeration<String> getKeys(){
        return resource.getKeys();
    }
}
View Code

 

2 利用javaMail實現郵件發送

  2.1 導入相關依賴

<!--郵件相關-->
        <!-- https://mvnrepository.com/artifact/javax.mail/mail -->
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
        </dependency>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>cn.xiangxu</groupId>
    <artifactId>springboottest</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springboottest</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--JSP相關-->
        <!-- https://mvnrepository.com/artifact/org.apache.tomcat.embed/tomcat-embed-jasper -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
        <!--JSTL相關-->
        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
        <!--郵件相關-->
        <!-- https://mvnrepository.com/artifact/javax.mail/mail -->
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
        </dependency>

        <!--工具相關-->
        <!--代碼生成工具-->
        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!--熱部署工具-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <!--通用工具包-->
        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.6</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <fork>true</fork>
                </configuration>
            </plugin>
        </plugins>
    </build>


</project>
View Code

  2.2 編寫郵件實體

    郵件實體就是將郵件利用Java對象的形式表示出來

package cn.xiangxu.springboottest.functionModule.mail;

import lombok.Data;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 郵件實體類:該類用於封裝發送郵件時需要的參數字段
 */
@Data
public class MailEntity implements Serializable{
    //此處填寫SMTP服務器
    private String smtpService;
    //設置端口號
    private String smtpPort;
    //設置發送郵箱
    private String fromMailAddress;
    // 設置發送郵箱的STMP口令
    private String fromMailStmpPwd;
    //設置郵件標題
    private String title;
    //設置郵件內容
    private String content;
    //內容格式(默認采用html)
    private String contentType;
    //接受郵件地址集合
    private List<String> list = new ArrayList<>();

}
View Code

  2.3 編寫郵件發送方的配置文件

    

  2.4 編寫讀取properties文件的工具類

package cn.xiangxu.springboottest.utils;

import java.util.Enumeration;
import java.util.Locale;
import java.util.ResourceBundle;

/**
 * 讀取properties文件工具類
 * 讀取發送郵件所需信息的properties文件的工具類
 */
public class PropertiesUtil {
    private final ResourceBundle resource;
    private final String fileName;

    /**
     * 構造函數實例化部分對象,獲取文件資源對象
     *
     * @param fileName
     */
    public PropertiesUtil(String fileName)
    {
        this.fileName = fileName;
        Locale locale = new Locale("zh", "CN");
        this.resource = ResourceBundle.getBundle(this.fileName, locale);
    }

    /**
     * 根據傳入的key獲取對象的值 2016年12月17日 上午10:19:55 getValue
     *
     * @param key properties文件對應的key
     * @return String 解析后的對應key的值
     */
    public String getValue(String key)
    {
        String message = this.resource.getString(key);
        return message;
    }

    /**
     * 獲取properties文件內的所有key值<br>
     * 2016年12月17日 上午10:21:20 getKeys
     *
     * @return
     */
    public Enumeration<String> getKeys(){
        return resource.getKeys();
    }
}
View Code

  2.5 編寫郵件內容類型的枚舉    

package cn.xiangxu.springboottest.functionModule.mail;

/**
 * 郵件模塊所需要的枚舉
 */
public enum MailContentTypeEnum {
    HTML("text/html;charset=UTF-8"), //html格式
    TEXT("text")
    ;
    private String value;

    MailContentTypeEnum(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }
}
View Code

  2.6 編寫郵件發送實體

    郵件發送實體就是將郵件發送方信息、郵件接收方信息、以及郵件類型整合成了一個java對象

package cn.xiangxu.springboottest.functionModule.mail;

import cn.xiangxu.springboottest.utils.PropertiesUtil;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.util.List;
import java.util.Properties;

/**
 * 郵件發送方實體類
 */
public class MailSender {
    // 郵件實體
    private static MailEntity mail = new MailEntity();

    /**
     * 設置郵件標題
     * @param title 標題信息
     * @return
     */
    public MailSender title(String title){
        mail.setTitle(title);
        return this;
    }

    /**
     * 設置郵件內容
     * @param content
     * @return
     */
    public MailSender content(String content)
    {
        mail.setContent(content);
        return this;
    }

    /**
     * 設置郵件格式
     * @param typeEnum
     * @return
     */
    public MailSender contentType(MailContentTypeEnum typeEnum)
    {
        mail.setContentType(typeEnum.getValue());
        return this;
    }

    /**
     * 設置請求目標郵件地址
     * @param targets
     * @return
     */
    public MailSender targets(List<String> targets)
    {
        mail.setList(targets);
        return this;
    }

    /**
     * 執行發送郵件
     * @throws Exception 如果發送失敗會拋出異常信息
     */
    public void send() throws Exception
    {
        // 01 基本信息驗證
        // 0101 郵件內容格式驗證,默認使用html內容發送
        if(mail.getContentType() == null)
            mail.setContentType(MailContentTypeEnum.HTML.getValue());

        // 0102 標題非空驗證,如果為空就拋出異常
        if(mail.getTitle() == null || mail.getTitle().trim().length() == 0)
        {
            throw new Exception("郵件標題沒有設置.調用title方法設置");
        }

        // 0103 內容為空驗證,如果為空就拋出異常
        if(mail.getContent() == null || mail.getContent().trim().length() == 0)
        {
            throw new Exception("郵件內容沒有設置.調用content方法設置");
        }

        // 0104 接收者郵箱地址驗證,如果沒有就拋出異常
        if(mail.getList().size() == 0)
        {
            throw new Exception("沒有接受者郵箱地址.調用targets方法設置");
        }

        //讀取/resource/mail_zh_CN.properties文件內容
        final PropertiesUtil properties = new PropertiesUtil("mail");
        // 創建Properties 類用於記錄郵箱的一些屬性
        final Properties props = new Properties();
        // 表示SMTP發送郵件,必須進行身份驗證
        props.put("mail.smtp.auth", "true");
        //此處填寫SMTP服務器
        props.put("mail.smtp.host", properties.getValue("mail.smtp.service"));
        //設置端口號,QQ郵箱給出了兩個端口465/587
        props.put("mail.smtp.port", properties.getValue("mail.smtp.prot"));
        // 設置發送郵箱
        props.put("mail.user", properties.getValue("mail.from.address"));
        // 設置發送郵箱的16位STMP口令
        props.put("mail.password", properties.getValue("mail.from.smtp.pwd"));

        // 構建授權信息,用於進行SMTP進行身份驗證
        Authenticator authenticator = new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                // 用戶名、密碼
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };
        // 使用環境屬性和授權信息,創建郵件會話
        Session mailSession = Session.getInstance(props, authenticator);
        // 創建郵件消息
        MimeMessage message = new MimeMessage(mailSession);
        // 設置發件人
        String nickName = MimeUtility.encodeText(properties.getValue("mail.from.nickname"));
        InternetAddress form = new InternetAddress(nickName + " <" + props.getProperty("mail.user") + ">");
        message.setFrom(form);

        // 設置郵件標題
        message.setSubject(mail.getTitle());
        //html發送郵件
        if(mail.getContentType().equals(MailContentTypeEnum.HTML.getValue())) {
            // 設置郵件的內容體
            message.setContent(mail.getContent(), mail.getContentType());
        }
        //文本發送郵件
        else if(mail.getContentType().equals(MailContentTypeEnum.TEXT.getValue())){
            message.setText(mail.getContent());
        }
        //發送郵箱地址
        List<String> targets = mail.getList();
        for(int i = 0;i < targets.size();i++){
            try {
                // 設置收件人的郵箱
                InternetAddress to = new InternetAddress(targets.get(i));
                message.setRecipient(Message.RecipientType.TO, to);
                // 最后當然就是發送郵件啦
                Transport.send(message);
            } catch (Exception e) {
                continue;
            }
        }
    }
}
View Code

  2.7 編寫測試類來發送郵件

    

@Test
    public void mailTest() throws Exception {
        new MailSender()
                .title("測試郵件發送")
                .content("504制造物聯網實驗室,重慶市大足區")
                .contentType(MailContentTypeEnum.TEXT)
                .targets(new ArrayList<String>(){{
                    add("412744267@qq.com");
                    add("cqdzwys@163.com");
                }})
                .send();
    }
View Code

  2.8 效果展示

    

   2.9 綜合應用

    在異常處理類中,對捕獲到的異常通過郵件發送給開發者 -> 在異常處理類中進行

 

 

 

 

 

  


免責聲明!

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



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