Spring Boot 发送邮件 javax.mail


本文基于Spring Boot  2.0.0.RELEASE。

首先,需要在pom文件中引入依赖

<dependency>
     <groupId>javax.mailgroupId>
     <artifactId>mailartifactId>
     <version>1.5.0-b01version>
dependency>

然后需要在项目的yml或者properties文件中配置发件人的邮箱地址、账号、密码等信息。

在resources目录下新建一个email.properties文件

#   开启debug调试
email.data.mailDebug=true
#   发送服务器需要身份验证
email.data.mailSmtpAuth=true
#   设置邮件服务器主机名
email.data.mailHost=smtp.163.com
#   发送邮件协议名称
email.data.mailTransportProtocol=smtp
#   账号
email.data.mailUsername=your_email@163.com
#   密码(授权码或者独立密码)
email.data.mailPassword=your_auth_word

这里要值得注意的是,163的邮箱(有可能包含126的邮箱),使用第三方发送邮件时需要在他们的邮箱系统中开启smtp/pop/imap的权限,具体如何开启就不再赘述,但密码一定要填写授权码。

同理,QQ邮箱的话,密码也不是填写QQ邮箱的密码,而是填写独立密码。

创建一个Properties类EmailProperties.java,获取Email的配置。

通过@Component将这个类添加到Spring IOC中。

通过@PropertySource,指定properties文件的位置,若这些配置卸载了application-xxx.properties下,则不需要这个注解。

通过@ConfigurationProperties,指定前缀,如此一来,只需要类中的属性名和properties文件中除前缀以外的名称对上就可以直接获取值。

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "email.data")
@PropertySource(value = "classpath:email.properties", encoding = "UTF-8")
public class EmailProperties {

    private String mailDebug;

    private String mailSmtpAuth;

    private String mailHost;

    private String mailTransportProtocol;

    private String mailUserName;

    private String mailPassword;

    public String getMailDebug() {
        return mailDebug;
    }

    public void setMailDebug(String mailDebug) {
        this.mailDebug = mailDebug;
    }

    public String getMailSmtpAuth() {
        return mailSmtpAuth;
    }

    public void setMailSmtpAuth(String mailSmtpAuth) {
        this.mailSmtpAuth = mailSmtpAuth;
    }

    public String getMailHost() {
        return mailHost;
    }

    public void setMailHost(String mailHost) {
        this.mailHost = mailHost;
    }

    public String getMailTransportProtocol() {
        return mailTransportProtocol;
    }

    public void setMailTransportProtocol(String mailTransportProtocol) {
        this.mailTransportProtocol = mailTransportProtocol;
    }

    public String getMailUserName() {
        return mailUserName;
    }

    public void setMailUserName(String mailUserName) {
        this.mailUserName = mailUserName;
    }

    public String getMailPassword() {
        return mailPassword;
    }

    public void setMailPassword(String mailPassword) {
        this.mailPassword = mailPassword;
    }
}

创建邮箱工具类EmailUtils.java

通过@Autowired 将邮箱配置注入,

import cnki.tpi.bean.EmailProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

@Component
@EnableConfigurationProperties(EmailProperties.class)
public class EmailUtils {

    @Autowired
    private EmailProperties emailProperties;

    public String SendEmailUtil(String receiveMail, String emailTitle, String emailContent){
        //发送人邮箱号码
        String mailUserName = emailProperties.getMailUserName();

        try {
            //1、创建参数配置, 用于连接邮件服务器的参数配置
            Properties prop = new Properties();
            //发送邮件协议名称
            prop.setProperty("mail.transport.protocol", emailProperties.getMailTransportProtocol());
            prop.setProperty("mail.smtp.host", emailProperties.getMailHost());//邮件服务器地址
            prop.setProperty("mail.smtp.auth", emailProperties.getMailSmtpAuth());//需要请求认证
            //prop.put("mail.smtp.port","587");
            prop.setProperty("mail.debug", emailProperties.getMailDebug());
            // 2. 根据参数配置,创建会话对象, 用于和邮件服务器交互
            Session session= Session.getInstance(prop);
            // 3. 创建一封邮件,发件人及收件人邮箱
            MimeMessage message = createMimeMessage(session,emailTitle,emailContent,mailUserName, receiveMail);
            // 4. 根据 Session 获取邮件传输对象
            Transport transport = session.getTransport();
            // 5. 使用 邮箱账号和密码(授权码)连接邮件服务器, 这里认证的邮箱必须与 message 中的发件人邮箱一致, 否则报错
            transport.connect(mailUserName, emailProperties.getMailPassword());
            // 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
            transport.sendMessage(message, message.getAllRecipients());
            // 7. 关闭连接
            transport.close();
        } catch (Exception e) {
            e.printStackTrace();
            return "ConnectError";
        }
        return "sucess";
    }

    public  MimeMessage createMimeMessage(Session session,String emailTitle,String emailContent, String sendMail, String receiveMail) throws Exception {
        //收件人昵称为收件邮箱去除后缀
        String resiveMailName = sendMail.substring(0,receiveMail.lastIndexOf("@"));

        // 1. 创建一封邮件
        MimeMessage message = new MimeMessage(session);

        // 2. From: 发件人
        message.setFrom(new InternetAddress(sendMail, "发件人名称", "UTF-8"));

        // 3. To: 收件人(可以增加多个收件人、抄送、密送)、收件人昵称
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, resiveMailName, "UTF-8"));

        // 4. Subject: 邮件主题
        message.setSubject(emailTitle,"UTF-8");

        // 5. Content: 邮件正文(可以使用html标签)
        message.setContent(emailContent, "text/html;charset=UTF-8");

        // 6. 设置发件时间
        message.setSentDate(new Date());

        // 7. 保存设置
        message.saveChanges();

        return message;
    }
}

最后创建一个测试类

import cnki.tpi.util.EmailUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("email")
public class EmailController {

    @Autowired
    private EmailUtils emailUtils;

    @RequestMapping("send")
    @ResponseBody
    public String sendEmail(){
        return emailUtils.SendEmailUtil("目标邮箱地址@163.com","测试邮件发送",
                "点击以下链接,跳转百度首页:https://www.baidu.com");
    }
}