不废话,直接上代码
思路: 继承JavaMailSenderImpl, 通过配置类, 创建bean, 因为后续可能会持续增加发件人, 所以直接将发件人信息配置在数据库, 然后项目启动时查询所有发件人信息, 循环创建bean,
根据类型自动注入, 因为有多个所以使用List<EMaiFormIMainServiceImpl> 接收
然后将LIst 转Map key= 发件人邮箱, value= 当前对象
使用时, 根据发件人邮箱,取出对应的bean实例
调用实例的.send((MimeMessage mimeMessage) -> {
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, Boolean.TRUE, StandardCharsets.UTF_8.name()); messageHelper.setFrom("发件人邮箱");
);
public class EMaiFormIMainServiceImpl extends JavaMailSenderImpl { private static final Properties p = new Properties(); static { p.setProperty("mail.smtp.auth", "true"); p.setProperty("mail.smtp.starttls.enable", "false"); p.setProperty("mail.smtp.starttls.required", "false"); } public EMaiFormIMainServiceImpl(String userName,String password, String host, Integer port, String defaultEncoding) { //发件人邮箱 super.setUsername(userName); super.setPassword(password); //服务器地址 super.setHost(host); //端口 super.setPort(port); super.setDefaultEncoding("UTF-8"); super.setJavaMailProperties(p); }
@Configuration public class EmailConfig { @Autowired private 发件人Repository repository; @Bean public List<EMaiFormIMainServiceImpl> getEMaiFormIMainServiceImplList() { List<发件人> list= repository.selectAll(); return list.stream().map(e->{ return new EMaiFormIMainServiceImpl(e.getUserName(),e.getPassword(),e.getHost(),e.getPort(),"UTF-8"); }).collect(Collectors.toList()); } }