You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Spring Boot中配置数量未知的多SMTP服务器?

动态配置多个SMTP邮件服务器(Spring Boot)

实现思路

核心是通过Spring的@ConfigurationProperties批量读取配置中的多组邮件服务器信息,动态创建对应的JavaMailSenderImpl实例并交由Spring容器管理,这样就能直接注入List<JavaMailSenderImpl>,新增服务器只需加配置无需改代码。

步骤1:定义配置属性类

创建映射多组邮件服务器配置的类,支持嵌套的SMTP属性:

import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.Map;

@ConfigurationProperties(prefix = "spring.mail")
public class MultipleMailProperties {
    // key对应配置中的first/second/third等标识,value是服务器详细配置
    private Map<String, MailServerProperties> servers;

    public static class MailServerProperties {
        private String host;
        private int port;
        private String username;
        private String password;
        private Map<String, String> properties;

        // 生成getter、setter方法
        public String getHost() { return host; }
        public void setHost(String host) { this.host = host; }
        public int getPort() { return port; }
        public void setPort(int port) { this.port = port; }
        public String getUsername() { return username; }
        public void setUsername(String username) { this.username = username; }
        public String getPassword() { return password; }
        public void setPassword(String password) { this.password = password; }
        public Map<String, String> getProperties() { return properties; }
        public void setProperties(Map<String, String> properties) { this.properties = properties; }
    }

    public Map<String, MailServerProperties> getServers() { return servers; }
    public void setServers(Map<String, MailServerProperties> servers) { this.servers = servers; }
}

步骤2:编写配置类,动态生成邮件发送器

通过配置类加载配置,遍历每组服务器信息创建JavaMailSenderImpl实例:

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Configuration
@EnableConfigurationProperties(MultipleMailProperties.class)
public class MultipleMailSenderConfig {

    @Bean
    public List<JavaMailSenderImpl> javaMailSenders(MultipleMailProperties properties) {
        return properties.getServers().values().stream()
                .map(this::createMailSender)
                .collect(Collectors.toList());
    }

    // 可选:注册Map形式的发送器,方便按名称获取
    @Bean
    public Map<String, JavaMailSenderImpl> mailSenderMap(MultipleMailProperties properties) {
        return properties.getServers().entrySet().stream()
                .collect(Collectors.toMap(Map.Entry::getKey, entry -> createMailSender(entry.getValue())));
    }

    private JavaMailSenderImpl createMailSender(MultipleMailProperties.MailServerProperties serverProps) {
        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        sender.setHost(serverProps.getHost());
        sender.setPort(serverProps.getPort());
        sender.setUsername(serverProps.getUsername());
        sender.setPassword(serverProps.getPassword());
        // 绑定SMTP附加属性
        if (serverProps.getProperties() != null) {
            sender.getJavaMailProperties().putAll(serverProps.getProperties());
        }
        return sender;
    }
}

步骤3:配置文件格式调整

将配置改为spring.mail.servers.xxx前缀,确保能被配置类正确读取:

spring.mail.servers.first.host=host1
spring.mail.servers.first.port=port1
spring.mail.servers.first.username=username1
spring.mail.servers.first.password=password1
spring.mail.servers.first.properties.mail.smtp.auth=true
spring.mail.servers.first.properties.mail.smtp.starttls.enable=true

spring.mail.servers.second.host=host2
spring.mail.servers.second.port=port2
spring.mail.servers.second.username=username2
spring.mail.servers.second.password=password2
spring.mail.servers.second.properties.mail.smtp.auth=true

# 新增服务器直接追加配置即可
spring.mail.servers.third.host=host3
spring.mail.servers.third.port=port3
spring.mail.servers.third.username=username3
spring.mail.servers.third.password=password3
spring.mail.servers.third.properties.mail.smtp.auth=true

步骤4:注入使用

按需求选择注入方式:

方式1:注入List批量使用

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.SimpleMailMessage;
import java.util.List;

// 业务类中注入
@Autowired
private List<JavaMailSenderImpl> javaMailSenders;

// 使用示例:用第一个发送器发邮件
public void sendTestMail() {
    SimpleMailMessage message = new SimpleMailMessage();
    message.setTo("recipient@example.com");
    message.setSubject("动态配置邮件测试");
    message.setText("通过动态配置的SMTP服务器发送");
    javaMailSenders.get(0).send(message);
}

方式2:注入Map按名称指定发送器

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import java.util.Map;

// 业务类中注入
@Autowired
private Map<String, JavaMailSenderImpl> mailSenderMap;

// 使用示例:指定"second"发送器发邮件
public void sendSpecifiedMail() {
    SimpleMailMessage message = new SimpleMailMessage();
    // 邮件内容设置...
    mailSenderMap.get("second").send(message);
}

注意事项

  • 确保使用Spring Boot 2.x及以上版本,支持@ConfigurationProperties的Map绑定特性
  • 如果需要更精细的控制,可以在MailServerProperties中添加更多字段(如默认编码、协议等)

内容的提问来源于stack exchange,提问作者gstackoverflow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 11:12:51