springboot(七)JavaMail发送邮件

JavaMail简介:  

  JavaMail是SUN提供给广大Java开发人员的一款邮件发送和接受的一款开源类库,支持常用的邮件协议,如:SMTP、POP3、IMAP,开发人员使用JavaMail编写邮件程序时,不再需要考虑底层的通讯细节如:Socket而是关注在逻辑层面。JavaMail可以发送各种复杂MIME格式的邮件内容,注意JavaMail仅支持JDK4及以上版本。虽然JavaMail是JDK的API但它并没有直接加入JDK中,所以我们需要另外添加依赖

本文目标:

  将Java提供的JavaMail类库与SpringBoot项目进行整合,并且简单封装下JavaMail类库。

  注意几个点:

  1、注意是哪个公司邮箱的服务器(这里用的是网易163)

 

   2、关于服务器的一些配置

一、建项目,直接建一个java项目就可以,这里建的springboot项目(目录)

二、依赖与配置文件mail_zh_CN.properties

<?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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.dyh</groupId>
    <artifactId>lesson_seven</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>lesson_seven</name>
    <description>Demo project for Spring Boot</description>

    <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</artifactId>
        </dependency>

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

        <!-- JavaMail依赖 -->
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
        </dependency>
    </dependencies>

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

</project>
View Code
#对应发送服务器的smtp服务地址
mail.smtp.service=smtp.163.com
#对应发送服务器的smtp服务器端口号
mail.smtp.prot=25
#发件人邮箱地址
mail.from.address=13592405250@163.com
#smtp授权密码,通过邮件中开启POP3/SMTP服务得到
mail.from.smtp.pwd=dyhgl19902012
#发件人邮箱显示昵称
mail.from.nickname=飞翔的蜗牛

三、代码实现

  1、MailEntity实体类

  MailEntity类来保存发送邮件时需要的参数字段

package com.dyh.bean;

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

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

    public String getSmtpService() {
        return smtpService;
    }

    public void setSmtpService(String smtpService) {
        this.smtpService = smtpService;
    }

    public String getSmtpPort() {
        return smtpPort;
    }

    public void setSmtpPort(String smtpPort) {
        this.smtpPort = smtpPort;
    }

    public String getFromMailAddress() {
        return fromMailAddress;
    }

    public void setFromMailAddress(String fromMailAddress) {
        this.fromMailAddress = fromMailAddress;
    }

    public String getFromMailStmpPwd() {
        return fromMailStmpPwd;
    }

    public void setFromMailStmpPwd(String fromMailStmpPwd) {
        this.fromMailStmpPwd = fromMailStmpPwd;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getContentType() {
        return contentType;
    }

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }

    public List<String> getList() {
        return list;
    }

    public void setList(List<String> list) {
        this.list = list;
    }
}
View Code

  2、MailContentTypeEnum枚举

  这是一个我自定义的枚举类型,枚举类型包含了邮件内容的类型,目前我仅仅添加了两种,一种是html另外一种则是text形式

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

  3、PropertiesUtil工具类

  PropertiesUtil是用于读取*.properties配置文件的工具类,使用JavaMail需要配置SMTP以及用户名、密码等也就是MailEntity内的字段,那么我们在/resource目录下创建一个名字叫mail.properties的配置文件,里面存放我们定义的邮件发送参数配置,这样方便修改,我分别贴出PropertiesUtil、mail.properties代码内容
package com.dyh.utils;

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

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

  4、核心代码类MailSender 

package com.dyh.core;

import com.dyh.bean.MailEntity;
import com.dyh.enums.MailContentTypeEnum;
import com.dyh.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
    {
        //默认使用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;
            }

        }
    }
}

  5、测试代码

public class TestMail {
    public static void main(String[] args) throws Exception
    {
        new MailSender()
                .title("测试SpringBoot发送邮件")
                .content("简单文本内容发送HelloWorld")
                .contentType(MailContentTypeEnum.TEXT)
                .targets(new ArrayList<String>(){{
                    add("13592405250@163.com");
                }})
                .send();
    }
}

 

三、昵称乱码问题解决

  1、修改InteiiJ IDEA工具的properties文件的编码,点击File->Setting->Editor->File Encodings将下面的Default encoding设置为UTF-8

 

  2、那么我们的mail.properties内使用ASCII编码进行配置昵称就可以了,具体中文如何转换ASCII,请大家访问tool.oschina.net/encode在线转换即可。

 

四、主要讲解了在SpringBoot项目内是如何使用JavaMail来进行发送简单邮件,简单封装了下MailSender类以及对象实体MailEntity,如果需要发送HTML内容的邮件修改contentType(MailContentTypeEnum.HTML)然后content("html代码")即可。

参考:
作者:恒宇少年
链接:https://www.jianshu.com/p/0991f0841b0a

posted @ 2019-01-17 21:57  杜大帅-Rebirth  阅读(398)  评论(0编辑  收藏  举报