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();
}
}

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>

  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<>(); }

  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();
}
}

  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;
}
}

  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;
}
}
}
}

  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();
}

  2.8 效果展示

    

  2.9 综合应用

    在异常处理类中,对捕获到的异常通过邮件发送给开发者 -> 在异常处理类中进行

  

SpringBoot11 读取properties文件、发送邮件的更多相关文章

  1. 五种方式让你在java中读取properties文件内容不再是难题

    一.背景 最近,在项目开发的过程中,遇到需要在properties文件中定义一些自定义的变量,以供java程序动态的读取,修改变量,不再需要修改代码的问题.就借此机会把Spring+SpringMVC ...

  2. java分享第十六天( java读取properties文件的几种方法&java配置文件持久化:static块的作用)

     java读取properties文件的几种方法一.项目中经常会需要读取配置文件(properties文件),因此读取方法总结如下: 1.通过java.util.Properties读取Propert ...

  3. 用eclipse做项目中常遇到的问题-如何创建并读取properties文件

    在用eclipse做项目开发的时候我们常常会将一些重要的内容写在配置文件里面, 特别是连接数据库的url,username,password等信息,我们常常会新建一个properties文件将所有信息 ...

  4. jsp读取properties文件

    jsp读取properties文件 jsp中读取properties文件,并把值设到js变量中: mpi.properties文件内容: MerchantID=00000820 CustomerEMa ...

  5. java读取.properties文件

    在web开发过程中,有些配置要保存到properties文件里,本章将给出一个工具类,用来方便读取properties文件. 案例: 1:config.properties文件 name=\u843D ...

  6. Java 读取Properties文件时应注意的路径问题

    1. 使用Class的getResourceAsStream()方法读取Properties文件(资源文件)的路径问题:  InputStream in = this.getClass().getRe ...

  7. Java的Properties类和读取.properties文件

    一..properties文件的作用 Properties属性文件在JAVA应用程序中是经常可以看得见的,也是特别重要的一类文件.它用来配置应用程序的一些信息,不过这些信息一般都是比较少的数据,没有必 ...

  8. Java-马士兵设计模式学习笔记-观察者模式-读取properties文件改成单例模式

    一.概述 1.目标:读取properties文件改成单例模式 二.代码 1.Test.java class WakenUpEvent{ private long time; private Strin ...

  9. Java读取Properties文件的六种方法

    使用J2SE API读取Properties文件的六种方法 1.使用java.util.Properties类的load()方法示例: InputStream in = lnew BufferedIn ...

随机推荐

  1. BZOJ5334: [Tjoi2018]数学计算

    BZOJ5334: [Tjoi2018]数学计算 https://lydsy.com/JudgeOnline/problem.php?id=5334 分析: 线段树按时间分治即可. 代码: #incl ...

  2. Codeforces 786C. Till I Collapse 主席树

    题目大意: 给定一个长度为\(n\)的序列,要求将其划分为最少的若干段使得每段中不同的数字的种数不超过\(k\). 对于 \(k = 1 .. n\)输出所有的答案. \(n \leq 10^5\) ...

  3. shell实现文件内容查询如输入姓名结果显示电话号码等信息

    #!/bin/awk -f BEGIN{FS=","; if(ARGC>2){name=ARGV[1];delete ARGV[1]} else{ echo "pl ...

  4. nodejs 接口跨域

    //设置跨域访问 //设置跨域访问 app.all('*', function(req, res, next) { res.header("Access-Control-Allow-Orig ...

  5. immutable学习

    React 做性能优化时有一个避免重复渲染的大招,就是使用 shouldComponentUpdate(),但它默认返回 true,即始终会执行 render() 方法,然后做 Virtual DOM ...

  6. Process使用

    最近在一个项目中,需要在C#中调用cmd窗口来执行一个命令,使用到了Process这个类,使用过程中遇到不少问题,好在终于解决了.赶紧记录下来. Process process = new Proce ...

  7. 在Linux上利用core dump和GDB调试segfault

    时常会遇到段错误(segfault),调试非常费劲,除了单元测试和基本测试外,有些时候是在在线环境下,没有基本开发和测试工具,这就需要调试的技能.以前介绍过使用strace进行系统调试和追踪<l ...

  8. acm 士兵杀敌(一)

    士兵杀敌(一) 时间限制:1000 ms  |  内存限制:65535 KB 难度:3   描述 南将军手下有N个士兵,分别编号1到N,这些士兵的杀敌数都是已知的. 小工是南将军手下的军师,南将军现在 ...

  9. websocket之三:Tomcat的WebSocket实现

    Tomcat自7.0.5版本开始支持WebSocket,并且实现了Java WebSocket规范(JSR356 ),而在7.0.5版本之前(7.0.2版本之后)则采用自定义API,即WebSocke ...

  10. MySQL 学习四 SQL优化

    MySQL逻辑架构: 第一层:客户端层,连接处理,授权认证,安全等功能.   第二层:核心层,查询解析,分析,优化,缓存,内置函数(时间,数学,加密),存储过程,触发器,视图   第三层:存储引擎.负 ...