SpringBoot整合邮箱

一.准备工作

1.1.开通邮箱SMTP服务

这里以qq邮箱为例,我们登录qq邮箱依次点击设置-常规-第三方服务-开启服务-生成授权码来开通邮箱SMTP服务。

springboot 邮箱配置javaconfig_后端

1.2.依赖导入

<!-- email依赖 -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

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

<dependency>
	<groupId>org.projectlombok</groupId>
	<artifactId>lombok</artifactId>
	<optional>true</optional>
</dependency>

1.3.配置application.properties文件

#发送者的邮箱,其他参数的注释详情见MailConfig.java文件
admin.email=********@qq.com
universe.mail.username=********@qq.com
universe.mail.password=********
universe.mail.host=smtp.qq.com
universe.mail.port=465
universe.mail.properties.mail.smtp.auth=true
universe.mail.properties.mail.smtp.socketFactory.port=465
universe.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
universe.mail.properties.mail.smtp.socketFactory.fallback=false
universe.mail.properties.mail.smtp.starttls.enable=true
universe.mail.properties.mail.smtp.starttls.required=true

1.4.创建MailConfig.java

package com.temperature.humidity.system.config.email;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

@Component
@Data
public class MailConfig {

    /**
     * SMTP服务器的登录用户。
     */
    @Value("${universe.mail.username}")
    private String username;

    /**
     * SMTP服务器的登录密码。
     */
    @Value("${universe.mail.password}")
    private String password;

    /**
     * SMTP服务器主机。例如,smtp.example.com.
     */
    @Value("${universe.mail.host}")
    private String host;

    /**
     * SMTP服务器端口。
     */
    @Value("${universe.mail.port}")
    private Integer port;

    /**
     * 如果为真,则尝试使用AUTH命令对用户进行身份验证。默认值为false。
     */
    @Value("${universe.mail.properties.mail.smtp.auth}")
    private String smtpAuth;

    /**
     * 指定的端口连接到在使用指定的套接字工厂。如果没有设置,将使用默认端口456
     */
    @Value("${universe.mail.properties.mail.smtp.socketFactory.port}")
    private String socketFactoryPort;

    /**
     * 指定实现javax.net.SocketFactory接口的类的名称,
     * 这个类将被用于创建SMTP的套接字
     */
    @Value("${universe.mail.properties.mail.smtp.socketFactory.class}")
    private String socketFactoryClass;

    /**
     * 如果设置为true,未能创建一个套接字使用指定的套接字
     * 工厂类将导致使用java.net.Socket创建的套接字类,
     * 默认值为true
     */
    @Value("${universe.mail.properties.mail.smtp.socketFactory.fallback}")
    private String socketFactoryFallback;

    /**
     * 使用 STARTTLS安全连接,STARTTLS是对纯文本通信协议的扩展。
     */
    @Value("${universe.mail.properties.mail.smtp.starttls.enable}")
    private String starttlsEnable;

    /**
     * 如果为真,则需要使用STARTTLS命令。如果服务器不支持STARTTLS命
     * 令,或者该命令失败,则connect方法将失败。默认值为false。
     */
    @Value("${universe.mail.properties.mail.smtp.starttls.required}")
    private String starttlsRequired;

    /**
     * SMTP全称为Simple Mail Transfer Protocol(简单邮件传输协议),
     * 它是一组用于从源地址到目的地址传输邮件的规范,通过它来控制邮件的中转
     * 方式。SMTP认证要求必须提供账号和密码才能登陆服务器,其设计目的在于
     * 避免用户受到垃圾邮件的侵扰。
     */
    private String protocol = "smtp";

    /**
     * 编码格式 默认为UTF-8。
     */
    private Charset defaultEncoding;

    /**
     * 会话JNDI名称。设置时,优先于其他会话设置。
     */
    private String jndiName;

    private static final Charset DEFAULT_CHARSET;

    public MailConfig() {
        this.defaultEncoding = DEFAULT_CHARSET;
    }

    static {
        DEFAULT_CHARSET = StandardCharsets.UTF_8;
    }

}

1.5.创建OurMail.java

package com.temperature.humidity.system.config.email;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

@Configuration
public class OurMail {

    @Autowired
    private MailConfig mailConfig;

    @Bean
    JavaMailSenderImpl mailSender() {
        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        this.applyProperties(mailConfig, sender);
        return sender;
    }

    private void applyProperties(MailConfig mailConfig, JavaMailSenderImpl sender) {
        sender.setHost(mailConfig.getHost());
        if (mailConfig.getPort() != null) {
            sender.setPort(mailConfig.getPort());
        }
        sender.setUsername(mailConfig.getUsername());
        sender.setPassword(mailConfig.getPassword());
        sender.setProtocol(mailConfig.getProtocol());
        if (mailConfig.getDefaultEncoding() != null) {
            sender.setDefaultEncoding(mailConfig.getDefaultEncoding().name());
        }

        sender.setJavaMailProperties(this.asProperties());
    }

    private Properties asProperties() {
        Properties properties = new Properties();
        Map<String, String> source = new HashMap<>();
        source.put("mail.smtp.auth", mailConfig.getSmtpAuth());
        source.put("mail.smtp.socketFactory.port", mailConfig.getSocketFactoryPort());
        source.put("mail.smtp.socketFactory.class", mailConfig.getSocketFactoryClass());
        source.put("mail.smtp.socketFactory.fallback", mailConfig.getSocketFactoryFallback());
        source.put("mail.smtp.starttls.enable", mailConfig.getStarttlsEnable());
        source.put("mail.smtp.starttls.required", mailConfig.getStarttlsRequired());
        properties.putAll(source);
        return properties;
    }

}

1.6.创建OurMailUtil.java

package com.temperature.humidity.system.common.utils;

import com.temperature.humidity.system.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.List;

/**
 * 邮箱工具类
 */
@Component
public class OurMailUtil {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${admin.email}")
    private String adminEmail;

    /**
     * 群发
     */
    public void sendMail(String subject, String text, List<User> users) throws MessagingException {
        String[] userEmail = new String[users.size()];
        for (int i = 0; i < users.size(); i++) {
            User user = users.get(i);
            userEmail[i] = user.getEmail();
        }
        sendMailPublic(subject, text, userEmail);

    }

    /**
     * 发给一个人
     */
    public void sendMailForOnePeople(String userEmail, String subject, String text) throws MessagingException {
        sendMailPublic(subject, text, userEmail);
    }
    
    private <T> void sendMailPublic(String subject, String text, T userEmail) throws MessagingException {
        //一个复杂的邮箱
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        //组装
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
        //即为邮件发送者,一般设置在配置文件中
        mimeMessageHelper.setFrom(adminEmail);
        if (userEmail instanceof String[]) {
            String[] userEmailArray = (String[]) userEmail;
            mimeMessageHelper.setTo(userEmailArray);
        }
        if (userEmail instanceof String) {
            String userEmailString = (String) userEmail;
            mimeMessageHelper.setTo((userEmailString));
        }
        //邮件主题
        mimeMessageHelper.setSubject(subject);
        //邮件内容
        mimeMessageHelper.setText(text, true);
        mailSender.send(mimeMessage);
    }

}

二.测试

2.1.创建EmailTestController.java

package com.temperature.humidity.system.controller;

import com.temperature.humidity.system.common.utils.OurMailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.MessagingException;

@RestController
@RequestMapping("/email")
public class EmailTestController {

    @Autowired
    private OurMailUtil ourMailUtil;

    @RequestMapping("/sent")
    public String sentEmail() {
        try {
            //要发送人的邮箱
            String toEmail = "********@qq.com";
            //邮箱主题
            String subject = "邮箱测试-html";
            //邮箱内容
            String text = "<p style='color:red'>我是红色</p>";
            ourMailUtil.sendMailForOnePeople(toEmail, subject, text);
            return "发送成功";
        } catch (MessagingException e) {
            return "发送失败!";
        }
    }

}

2.2.测试接口

我们的服务启动成功之后,打开postman输入http://127.0.0.1:8080/email/sent访问我们的邮箱-html发送测试接口,我们可以看到服务器返回了发送成功的消息。

springboot 邮箱配置javaconfig_java_02

我们登录被发送人邮箱可以看到这条消息,则证明测试成功。

springboot 邮箱配置javaconfig_java_03