简单介绍
JavaMail是SUN公司提供给广大Java开发人员的一款邮件发送和接收的开源类库,支持常用的邮件协议,如:SMTP、POP3、IMAP,开发人员使用JavaMail编写邮件程序时,不再需要考虑底层的通讯细节如:Socket,而是关注在逻辑层面。JavaMail可以发送各种复杂MIME格式的邮件内容,注意JavaMail仅支持JDK4及以上版本。
构建项目
本章项目无关Web相关内容,所以创建项目时选择Jar形式创建。虽然JavaMail是JDK的API但它并没有直接加入JDK中,所以我们需要另外添加依赖。
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- JavaMail依赖 -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
封装JavaMail
1、编写实体类MailEntity来保存发送邮件时需要的参数字段
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<>();
get/set...
2、创建一个邮件发送者实体MailSender来配置发送邮件参数以及执行发送邮件
public class MailSender {
private static MailEntity mail = new MailEntity(); //邮件实体
//设置邮件标题
public MailSender title(String title){
mail.setTitle(title);
return this;
}
//设置邮件内容
public MailSender content(String content)
{
mail.setContent(content);
return this;
}
//设置邮件格式
public MailSender contentType(MailContentTypeEnum typeEnum)
{
mail.setContentType(typeEnum.getValue());
return this;
}
//设置请求目标邮件地址
public MailSender targets(List<String> targets)
{
mail.setList(targets);
return this;
}
/**
* 执行发送邮件
* @throws Exception 如果发送失败会抛出异常信息
*/
public void send() throws Exception
{
//默认使用html内容发送
if(mail.getContentType() == null)
mail.setContentType(MailContentTypeEnum.HTML.getValue());
if(mail.getTitle() == null || mail.getTitle().trim().length() == 0)
{
throw new Exception("邮件标题没有设置.调用title方法设置");
}
if(mail.getContent() == null || mail.getContent().trim().length() == 0)
{
throw new Exception("邮件内容没有设置.调用content方法设置");
}
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;
}
}
}
}
3、定义一个枚举类型MailContentTypeEnum包含了邮件内容的类型,目前我只添加了html和text这两种形式。
public enum MailContentTypeEnum {
HTML("text/html;charset=UTF-8"), TEXT("text");
private String value;
MailContentTypeEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
4、创建工具类PropertiesUtil
PropertiesUtil用于读取*.properties配置文件的工具类,使用JavaMail需要配置SMTP以及用户名、密码等也就是MailEntity内的字段,那么我们在/resource目录下创建一个名字叫mail.properties的配置文件,里面存放我们定义的邮件发送参数配置,这样方便修改
public class PropertiesUtil {
private final ResourceBundle resource;
private final String fileName;
//构造函数实例化部分对象,获取文件资源对象
public PropertiesUtil(String fileName)
{
this.fileName = fileName;
Locale locale = new Locale("zh", "CN");
this.resource = ResourceBundle.getBundle(this.fileName, locale);
}
/**
* 根据传入的key获取对象的值
* @param key properties文件对应的key
* @return String 解析后的对应key的值
*/
public String getValue(String key)
{
String message = this.resource.getString(key);
return message;
}
//获取properties文件内的所有key值
public Enumeration<String> getKeys(){
return resource.getKeys();
}
}
mail.properties
mail.smtp.service=smtp.qq.com
mail.smtp.prot=587
mail.from.address=123@qq.com
mail.from.smtp.pwd=***********
mail.from.nickname=Mir Li
注意:如果第一次使用QQ邮箱的SMTP服务,请点击“开启”POP3以及SMTP服务并且按照提示步骤完成获取“授权码”即可,授权码就是发送邮件参数的smtp.pwd属性。
测试邮件发送
创建一个TestMail类来作为测试入口,因为我们的项目是jar形式,所以我们直接新建一个main方法直接调用发送邮件就可以了。
public class TestMail {
public static void main(String[] args) throws Exception
{
new MailSender()
.title("测试SpringBoot发送邮件")
.content("简单文本内容发送")
.contentType(MailContentTypeEnum.TEXT)
.targets(new ArrayList<String>(){{
add("123@163.com");
}})
.send();
}
}
如果昵称出现乱码:修改InteiiJ IDEA工具的properties文件的编码,点击File->Setting->Editor->File Encodings将下面的Default encoding设置为UTF-8即可。
中文转换ASCII码可以访问tool.oschina.net/encode在线转换
总结
上述内容就是本章的所有讲解,本章主要讲解了在SpringBoot项目内是如何使用JavaMail来进行发送简单邮件,简单封装了下MailSender类以及对象实体MailEntity,如果需要发送HTML内容的邮件修改contentType(MailContentTypeEnum.HTML)然后content(“html代码”)即可。