Prechádzať zdrojové kódy

营销计划关联发件箱逻辑和是否拒收逻辑,同步问题,发件限制逻辑

chenkq 3 týždňov pred
rodič
commit
c67afb7922
29 zmenil súbory, kde vykonal 1468 pridanie a 51 odobranie
  1. 5 0
      storlead-framework/storlead-common/src/main/java/com/storlead/framework/common/constant/RedisKeySaltConstant.java
  2. 72 0
      storlead-mail-api/src/main/java/com/storlead/mail/crm/MailApiController.java
  3. 16 1
      storlead-mail-api/src/main/java/com/storlead/mail/mkt/MktMailApiController.java
  4. 10 0
      storlead-mail-api/src/main/resources/application.yml
  5. 8 0
      storlead-mail/storlead-mail-common/src/main/java/com/storlead/sales/mail/common/entity/SmtpPopSettingsEntity.java
  6. 45 0
      storlead-mail/storlead-mail-common/src/main/java/com/storlead/sales/mail/common/entity/SystemConfigItemEntity.java
  7. 10 0
      storlead-mail/storlead-mail-common/src/main/java/com/storlead/sales/mail/common/mapper/SystemConfigItemMapper.java
  8. 49 0
      storlead-mail/storlead-mail-common/src/main/java/com/storlead/sales/mail/common/pojo/EmailAddressValidateResult.java
  9. 39 0
      storlead-mail/storlead-mail-common/src/main/java/com/storlead/sales/mail/common/service/EmailAddressValidateService.java
  10. 16 0
      storlead-mail/storlead-mail-common/src/main/java/com/storlead/sales/mail/common/service/SystemConfigItemService.java
  11. 218 0
      storlead-mail/storlead-mail-common/src/main/java/com/storlead/sales/mail/common/service/impl/EmailAddressValidateServiceImpl.java
  12. 3 0
      storlead-mail/storlead-mail-common/src/main/java/com/storlead/sales/mail/common/service/impl/MailAccountBizServiceImpl.java
  13. 75 0
      storlead-mail/storlead-mail-common/src/main/java/com/storlead/sales/mail/common/service/impl/SystemConfigItemServiceImpl.java
  14. 2 0
      storlead-mail/storlead-mail-common/src/main/resources/mapper/SmtpPopSettingsMapper.xml
  15. 7 0
      storlead-mail/storlead-mail-common/src/main/resources/sql/smtp_pop_settings_drop_temp_disable.sql
  16. 36 0
      storlead-mail/storlead-mail-common/src/main/resources/sql/system_config_item_and_account_health.sql
  17. 38 0
      storlead-mail/storlead-mail-dispatch/src/main/java/com/storlead/sales/mail/dispatch/MktSendQuotaResetJob.java
  18. 26 0
      storlead-mail/storlead-mail-mkt/src/main/java/com/storlead/sales/mail/mkt/config/MktMailSendProperties.java
  19. 31 0
      storlead-mail/storlead-mail-mkt/src/main/java/com/storlead/sales/mail/mkt/config/MktSendQuotaBootstrap.java
  20. 2 0
      storlead-mail/storlead-mail-mkt/src/main/java/com/storlead/sales/mail/mkt/receive/MktMailReceivePersist.java
  21. 20 0
      storlead-mail/storlead-mail-mkt/src/main/java/com/storlead/sales/mail/mkt/service/MktSendAccountHealthService.java
  22. 25 0
      storlead-mail/storlead-mail-mkt/src/main/java/com/storlead/sales/mail/mkt/service/MktSendAccountSelector.java
  23. 53 0
      storlead-mail/storlead-mail-mkt/src/main/java/com/storlead/sales/mail/mkt/service/MktSendQuotaService.java
  24. 151 23
      storlead-mail/storlead-mail-mkt/src/main/java/com/storlead/sales/mail/mkt/service/impl/MktMailMessageServiceImpl.java
  25. 72 26
      storlead-mail/storlead-mail-mkt/src/main/java/com/storlead/sales/mail/mkt/service/impl/MktMailStatusServiceImpl.java
  26. 107 0
      storlead-mail/storlead-mail-mkt/src/main/java/com/storlead/sales/mail/mkt/service/impl/MktSendAccountHealthServiceImpl.java
  27. 144 0
      storlead-mail/storlead-mail-mkt/src/main/java/com/storlead/sales/mail/mkt/service/impl/MktSendAccountSelectorImpl.java
  28. 154 0
      storlead-mail/storlead-mail-mkt/src/main/java/com/storlead/sales/mail/mkt/service/impl/MktSendQuotaServiceImpl.java
  29. 34 1
      storlead-mail/storlead-mail-mkt/src/main/java/com/storlead/sales/mail/mkt/util/MktMailSender.java

+ 5 - 0
storlead-framework/storlead-common/src/main/java/com/storlead/framework/common/constant/RedisKeySaltConstant.java

@@ -22,4 +22,9 @@ public class RedisKeySaltConstant {
      * 操作成功
      */
     public static final String REDIS_LOGIN_VALID_CODE_KEY = "redis_login_valid_code_key_";
+
+    /**
+     * 营销邮件当天剩余发送额度(全站共用,值为剩余可发封数)
+     */
+    public static final String MKT_DAILY_SEND_REMAINING = "mkt:daily:send:remaining";
 }

+ 72 - 0
storlead-mail-api/src/main/java/com/storlead/mail/crm/MailApiController.java

@@ -26,6 +26,8 @@ import com.storlead.sales.mail.crm.enums.EmailBoxEnum;
 import com.storlead.sales.mail.crm.enums.SendStatus;
 import com.storlead.sales.mail.crm.pojo.*;
 import com.storlead.sales.mail.common.properties.MailFileProperties;
+import com.storlead.sales.mail.crm.pojo.vo.NewMailCountTipVO;
+import com.storlead.sales.mail.crm.pojo.vo.NewMailTipVO;
 import com.storlead.sales.mail.crm.service.*;
 import com.storlead.sales.mail.crm.support.MailOwnershipGuard;
 import com.storlead.sales.mail.crm.util.FileHelper;
@@ -120,6 +122,76 @@ public class MailApiController {
         }
     }
 
+    @PostMapping(value = "/get_new_mail")
+    @ApiOperation(value = "获取未读和最新的邮件", notes = "获取邮箱未读数")
+    @ApiResponses({
+            @ApiResponse(code = 200, message = "", response = NewMailCountTipVO.class)
+    })
+    public Result getNewMail() {
+
+        Long currentUserId = LoginUserUtil.getCurrentUserId();
+        SmtpPopSettingsEntity smtpPop = smtpPopSettingsService.getDefaultSmtpPop(currentUserId);
+        if (Objects.isNull(currentUserId) || Objects.isNull(smtpPop)) {
+            return Result.result("请先配置邮箱");
+        }
+        LambdaQueryWrapper<SmtpPopSettingsEntity> queryWrapper1 = new LambdaQueryWrapper();
+        queryWrapper1.select(SmtpPopSettingsEntity::getId);
+        queryWrapper1.eq(SmtpPopSettingsEntity::getIsDelete,0);
+        queryWrapper1.eq(SmtpPopSettingsEntity::getOwnerBy,currentUserId);
+        List<SmtpPopSettingsEntity> smtpPops = smtpPopSettingsService.list(queryWrapper1);
+
+        NewMailTipVO tipVO = new NewMailTipVO();
+        LambdaQueryWrapper<EmailsEntity> queryWrapper = new LambdaQueryWrapper();
+        queryWrapper.select(EmailsEntity::getId);
+        queryWrapper.eq(EmailsEntity::getOwnerBy, currentUserId);
+        if (!CollectionUtils.isEmpty(smtpPops)) {
+            queryWrapper.in(EmailsEntity::getSmtpPopId, smtpPops.stream().map(SmtpPopSettingsEntity::getId).collect(Collectors.toList()));
+        }
+        queryWrapper.eq(EmailsEntity::getFolder, EmailBoxEnum.INBOX.code);
+        queryWrapper.eq(EmailsEntity::getIsTrash, Integer.valueOf(0));
+        queryWrapper.eq(EmailsEntity::getIsRead, Integer.valueOf(0));
+        queryWrapper.eq(EmailsEntity::getIsDelete, Integer.valueOf(0));
+        queryWrapper.ne(EmailsEntity::getFrom, "system@storlead.com");
+        Integer unReadCount = emailsService.count(queryWrapper);
+        tipVO.setUnReadCount(unReadCount);
+        queryWrapper.select(EmailsEntity::getId,EmailsEntity::getSubject);
+        UserMailTrackRecordEntity record = mailTrackRecordService.getOne(new LambdaQueryWrapper<UserMailTrackRecordEntity>().eq(UserMailTrackRecordEntity::getOwnerBy, currentUserId).eq(UserMailTrackRecordEntity::getSmtpPopId, smtpPop.getId()).last("limit 1"));
+        if (Objects.isNull(record)) {
+            record = new UserMailTrackRecordEntity();
+            queryWrapper.orderByDesc(EmailsEntity::getId);
+            queryWrapper.last("limit 1");
+            EmailsEntity maxEmail = emailsService.getOne(queryWrapper);
+            if (Objects.nonNull(maxEmail)) {
+                record.setMaxMailId(maxEmail.getId());
+                record.setMessageId(maxEmail.getMessageId());
+                record.setSmtpPopId(smtpPop.getId());
+                record.setOwnerBy(currentUserId);
+                mailTrackRecordService.saveOrUpdate(record);
+            }
+            queryWrapper.last("limit 5");
+            if (unReadCount > 0) {
+                List<EmailsEntity> entities = emailsService.list(queryWrapper);
+                tipVO.setMaills(entities);
+            }
+            return Result.result(tipVO);
+        } else {
+            queryWrapper.gt(EmailsEntity::getId, record.getMaxMailId());
+            queryWrapper.last("limit 5");
+            List<EmailsEntity> entities = emailsService.list(queryWrapper);
+            if (CollectionUtils.isEmpty(entities)) {
+                return Result.result(tipVO);
+            } else {
+                tipVO.setMaills(entities);
+                Optional<EmailsEntity> maxEntity = entities.stream()
+                        .max(Comparator.comparing(EmailsEntity::getId));
+                record.setMaxMailId(maxEntity.get().getId());
+                mailTrackRecordService.saveOrUpdate(record);
+                return Result.result(tipVO);
+            }
+        }
+    }
+
+
     @PostMapping(value = "/asyn_send_mail")
     @ApiOperation(value = "发送邮件")
     @ApiResponses({

+ 16 - 1
storlead-mail-api/src/main/java/com/storlead/mail/mkt/MktMailApiController.java

@@ -10,6 +10,8 @@ import com.storlead.sales.mail.common.entity.MailTempAttachmentEntity;
 import com.storlead.sales.mail.common.entity.SmtpPopSettingsEntity;
 import com.storlead.sales.mail.common.enums.MailSceneEnum;
 import com.storlead.sales.mail.common.properties.MailFileProperties;
+import com.storlead.sales.mail.common.pojo.EmailAddressValidateResult;
+import com.storlead.sales.mail.common.service.EmailAddressValidateService;
 import com.storlead.sales.mail.common.service.MailAccountBizService;
 import com.storlead.sales.mail.common.service.MailTempAttachmentService;
 import com.storlead.sales.mail.common.util.SafeFilePathResolver;
@@ -78,6 +80,9 @@ public class MktMailApiController {
     @Resource
     private MailFileProperties mailFileProperties;
 
+    @Resource
+    private EmailAddressValidateService emailAddressValidateService;
+
     @PostMapping("/file/cache_mail_file")
     @ApiOperation("缓存营销邮件临时附件(scene=MKT)")
     public Result<?> cacheMailFile(@RequestParam("files") List<MultipartFile> files,
@@ -200,7 +205,7 @@ public class MktMailApiController {
     }
 
     @PostMapping("/send")
-    @ApiOperation("发送营销邮件(单封;默认同步等待投递结果;async=true 异步投递+回调;黑名单收件人直接拒绝)")
+    @ApiOperation("发送营销邮件(单封;默认同步等待投递结果;async=true 异步投递+回调;黑名单收件人直接拒绝;发信前校验邮箱格式与域名)")
     public Result<?> send(@RequestBody MktSendMailDTO dto) {
         Long userId = LoginUserUtil.getCurrentUserId();
         if (Objects.isNull(userId)) {
@@ -214,6 +219,16 @@ public class MktMailApiController {
         }
     }
 
+    @GetMapping("/validate_email")
+    @ApiOperation("校验邮箱是否格式正确、域名是否具备收信能力(降低退信;不能 100% 证明账号真实存在)")
+    public Result<?> validateEmail(@RequestParam("email") String email,
+                                   @RequestParam(value = "checkDomain", required = false) Boolean checkDomain) {
+        EmailAddressValidateResult result = checkDomain == null
+                ? emailAddressValidateService.validate(email)
+                : emailAddressValidateService.validate(email, checkDomain);
+        return Result.result(result);
+    }
+
     @PostMapping("/dispatch_sent")
     @ApiOperation("发送营销邮件(单封;默认同步等待投递结果;async=true 异步投递+回调)")
     public Result<?> dispatchSent(@RequestBody MktSendMailDTO dto) {

+ 10 - 0
storlead-mail-api/src/main/resources/application.yml

@@ -47,6 +47,16 @@ storlead:
     # 最终像素:{track-base-url}{server.servlet.context-path}/mkt/track/{token}
     # 例 test:https://email.test.storlead.com + /router/email + /mkt/track/{token}
     track-base-url: ${domainname:}
+    # 发信前邮箱校验:格式 + DNS MX/A(域名是否具备收信能力)
+    validate:
+      check-domain: true
+      domain-cache-seconds: 600
+    mkt:
+      # 日发送限额改由 system_config_item(mkt.daily.send.limit / remaining)+ Redis 管理
+      # 首选账号不可用时,额外轮询切换的邮箱个数
+      send-account-retry: 2
+      # 每天零点:remaining=limit 并刷新 Redis
+      quota-reset-cron: "0 0 0 * * ?"
     integration:
       enabled: true
       poll-interval-ms: 30000

+ 8 - 0
storlead-mail/storlead-mail-common/src/main/java/com/storlead/sales/mail/common/entity/SmtpPopSettingsEntity.java

@@ -133,4 +133,12 @@ public class SmtpPopSettingsEntity extends SysBaseField {
     @ApiModelProperty(value = "是否允许收信:1是 0否")
     @TableField("enable_receive")
     private Integer enableReceive;
+
+    @ApiModelProperty(value = "是否允许发信:1是 0否(账号级故障置0后需人工确认恢复)")
+    @TableField("enable_send")
+    private Integer enableSend;
+
+    @ApiModelProperty(value = "不可发送原因(enable_send=0 时填写,人工确认后清空)")
+    @TableField("send_disable_reason")
+    private String sendDisableReason;
 }

+ 45 - 0
storlead-mail/storlead-mail-common/src/main/java/com/storlead/sales/mail/common/entity/SystemConfigItemEntity.java

@@ -0,0 +1,45 @@
+package com.storlead.sales.mail.common.entity;
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableField;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
+import com.storlead.framework.mybatis.entity.SysBaseField;
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+import lombok.EqualsAndHashCode;
+import lombok.experimental.Accessors;
+
+/**
+ * 系统变量配置(system_config_item)。
+ */
+@Data
+@EqualsAndHashCode(callSuper = true)
+@Accessors(chain = true)
+@TableName("system_config_item")
+@ApiModel(value = "SystemConfigItemEntity", description = "系统变量配置")
+public class SystemConfigItemEntity extends SysBaseField {
+
+    private static final long serialVersionUID = 1L;
+
+    /** 营销当天发送限额 */
+    public static final String KEY_MKT_DAILY_SEND_LIMIT = "mkt.daily.send.limit";
+    /** 营销当天剩余额度 */
+    public static final String KEY_MKT_DAILY_SEND_REMAINING = "mkt.daily.send.remaining";
+
+    @TableId(value = "id", type = IdType.AUTO)
+    private Long id;
+
+    @ApiModelProperty("配置键")
+    @TableField("config_key")
+    private String configKey;
+
+    @ApiModelProperty("配置值")
+    @TableField("config_value")
+    private String configValue;
+
+    @ApiModelProperty("说明")
+    @TableField("remark")
+    private String remark;
+}

+ 10 - 0
storlead-mail/storlead-mail-common/src/main/java/com/storlead/sales/mail/common/mapper/SystemConfigItemMapper.java

@@ -0,0 +1,10 @@
+package com.storlead.sales.mail.common.mapper;
+
+import com.storlead.framework.mybatis.mapper.MyBaseMapper;
+import com.storlead.sales.mail.common.entity.SystemConfigItemEntity;
+
+/**
+ * 系统变量配置 Mapper。
+ */
+public interface SystemConfigItemMapper extends MyBaseMapper<SystemConfigItemEntity> {
+}

+ 49 - 0
storlead-mail/storlead-mail-common/src/main/java/com/storlead/sales/mail/common/pojo/EmailAddressValidateResult.java

@@ -0,0 +1,49 @@
+package com.storlead.sales.mail.common.pojo;
+
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+
+/**
+ * 邮箱地址校验结果。
+ * <p>
+ * 说明:可证明格式正确、域名具备收信能力(MX/A);无法 100% 证明邮箱账号真实存在。
+ */
+@Data
+@ApiModel("邮箱地址校验结果")
+public class EmailAddressValidateResult {
+
+    @ApiModelProperty("规范化后的邮箱(小写 trim)")
+    private String email;
+
+    @ApiModelProperty("是否可通过校验(格式正确,且 MX 检查开启时域名可收信)")
+    private boolean valid;
+
+    @ApiModelProperty("格式是否合法")
+    private boolean formatOk;
+
+    @ApiModelProperty("域名是否具备收信能力(MX 或 A/AAAA);未做域名检查时为 null")
+    private Boolean domainOk;
+
+    @ApiModelProperty("失败原因;通过时为空")
+    private String reason;
+
+    public static EmailAddressValidateResult ok(String email, Boolean domainOk) {
+        EmailAddressValidateResult r = new EmailAddressValidateResult();
+        r.setEmail(email);
+        r.setValid(true);
+        r.setFormatOk(true);
+        r.setDomainOk(domainOk);
+        return r;
+    }
+
+    public static EmailAddressValidateResult fail(String email, boolean formatOk, Boolean domainOk, String reason) {
+        EmailAddressValidateResult r = new EmailAddressValidateResult();
+        r.setEmail(email);
+        r.setValid(false);
+        r.setFormatOk(formatOk);
+        r.setDomainOk(domainOk);
+        r.setReason(reason);
+        return r;
+    }
+}

+ 39 - 0
storlead-mail/storlead-mail-common/src/main/java/com/storlead/sales/mail/common/service/EmailAddressValidateService.java

@@ -0,0 +1,39 @@
+package com.storlead.sales.mail.common.service;
+
+import com.storlead.sales.mail.common.pojo.EmailAddressValidateResult;
+
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * 邮箱地址校验工具服务:格式合法性 + 域名收信能力(DNS MX/A),用于发信前降低退信风险。
+ */
+public interface EmailAddressValidateService {
+
+    /**
+     * 校验单个邮箱。
+     *
+     * @param checkDomain 是否做 DNS MX/A 检查
+     */
+    EmailAddressValidateResult validate(String email, boolean checkDomain);
+
+    /**
+     * 默认开启域名检查的校验。
+     */
+    EmailAddressValidateResult validate(String email);
+
+    /**
+     * 主收件人必须可投递,否则抛业务异常。
+     */
+    void assertDeliverable(String email);
+
+    /**
+     * 过滤逗号分隔地址中不可投递的,返回保留的地址串(可能为空)。
+     */
+    String retainDeliverable(String emailsCsv);
+
+    /**
+     * 批量校验。
+     */
+    List<EmailAddressValidateResult> validateAll(Collection<String> emails, boolean checkDomain);
+}

+ 16 - 0
storlead-mail/storlead-mail-common/src/main/java/com/storlead/sales/mail/common/service/SystemConfigItemService.java

@@ -0,0 +1,16 @@
+package com.storlead.sales.mail.common.service;
+
+import com.storlead.framework.mybatis.service.MyBaseService;
+import com.storlead.sales.mail.common.entity.SystemConfigItemEntity;
+
+/**
+ * 系统变量配置:按 config_key 读写。
+ */
+public interface SystemConfigItemService extends MyBaseService<SystemConfigItemEntity> {
+
+    String getValue(String configKey);
+
+    Integer getIntValue(String configKey, Integer defaultValue);
+
+    void setValue(String configKey, String configValue);
+}

+ 218 - 0
storlead-mail/storlead-mail-common/src/main/java/com/storlead/sales/mail/common/service/impl/EmailAddressValidateServiceImpl.java

@@ -0,0 +1,218 @@
+package com.storlead.sales.mail.common.service.impl;
+
+import com.storlead.framework.web.exception.WebException;
+import com.storlead.sales.mail.common.pojo.EmailAddressValidateResult;
+import com.storlead.sales.mail.common.service.EmailAddressValidateService;
+import lombok.extern.log4j.Log4j2;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Service;
+import org.springframework.util.CollectionUtils;
+import org.springframework.util.StringUtils;
+
+import javax.mail.internet.AddressException;
+import javax.mail.internet.InternetAddress;
+import javax.naming.NamingEnumeration;
+import javax.naming.NamingException;
+import javax.naming.directory.Attribute;
+import javax.naming.directory.Attributes;
+import javax.naming.directory.DirContext;
+import javax.naming.directory.InitialDirContext;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Hashtable;
+import java.util.List;
+import java.util.Locale;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.regex.Pattern;
+
+/**
+ * 邮箱校验:
+ * 1) 格式(InternetAddress + 正则);
+ * 2) 可选 DNS:查 MX,无 MX 再查 A/AAAA(部分域名无 MX 也可收信)。
+ * <p>
+ * 不做 SMTP RCPT 探测(多数服务商禁用且易被风控),因此不能 100% 证明邮箱账号存在,
+ * 但可挡住明显错误格式与无收信能力的域名,降低退信。
+ */
+@Log4j2
+@Service
+public class EmailAddressValidateServiceImpl implements EmailAddressValidateService {
+
+    private static final Pattern SIMPLE_EMAIL = Pattern.compile(
+            "^[A-Za-z0-9_!#$%&'*+/=?`{|}~^.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$");
+
+    /** 域名 DNS 结果短缓存,降低发信高峰重复查询 */
+    private final ConcurrentHashMap<String, CacheEntry> domainCache = new ConcurrentHashMap<>();
+
+    @Value("${storlead.mail.validate.check-domain:true}")
+    private boolean defaultCheckDomain;
+
+    @Value("${storlead.mail.validate.domain-cache-seconds:600}")
+    private long domainCacheSeconds;
+
+    @Override
+    public EmailAddressValidateResult validate(String email) {
+        return validate(email, defaultCheckDomain);
+    }
+
+    @Override
+    public EmailAddressValidateResult validate(String email, boolean checkDomain) {
+        if (!StringUtils.hasText(email)) {
+            return EmailAddressValidateResult.fail(email, false, null, "邮箱为空");
+        }
+        String normalized = email.trim().toLowerCase(Locale.ROOT);
+        if (!isFormatOk(normalized)) {
+            return EmailAddressValidateResult.fail(normalized, false, null, "邮箱格式不正确");
+        }
+        if (!checkDomain) {
+            return EmailAddressValidateResult.ok(normalized, null);
+        }
+        String domain = extractDomain(normalized);
+        if (!StringUtils.hasText(domain)) {
+            return EmailAddressValidateResult.fail(normalized, true, false, "无法解析邮箱域名");
+        }
+        boolean domainOk = hasMailExchanger(domain);
+        if (!domainOk) {
+            return EmailAddressValidateResult.fail(normalized, true, false,
+                    "邮箱域名无收信记录(无 MX/A),可能无法投递");
+        }
+        return EmailAddressValidateResult.ok(normalized, true);
+    }
+
+    @Override
+    public void assertDeliverable(String email) {
+        EmailAddressValidateResult result = validate(email, defaultCheckDomain);
+        if (!result.isValid()) {
+            throw new WebException(StringUtils.hasText(result.getReason())
+                    ? result.getReason()
+                    : "收件邮箱无效");
+        }
+    }
+
+    @Override
+    public String retainDeliverable(String emailsCsv) {
+        if (!StringUtils.hasText(emailsCsv)) {
+            return emailsCsv;
+        }
+        List<String> kept = new ArrayList<>();
+        for (String part : emailsCsv.split("[,;]")) {
+            if (!StringUtils.hasText(part)) {
+                continue;
+            }
+            EmailAddressValidateResult r = validate(part.trim(), defaultCheckDomain);
+            if (r.isValid()) {
+                kept.add(r.getEmail());
+            } else {
+                log.info("mkt/email validate drop address, email={}, reason={}",
+                        part.trim(), r.getReason());
+            }
+        }
+        return kept.isEmpty() ? "" : String.join(",", kept);
+    }
+
+    @Override
+    public List<EmailAddressValidateResult> validateAll(Collection<String> emails, boolean checkDomain) {
+        if (CollectionUtils.isEmpty(emails)) {
+            return Collections.emptyList();
+        }
+        List<EmailAddressValidateResult> list = new ArrayList<>(emails.size());
+        for (String email : emails) {
+            list.add(validate(email, checkDomain));
+        }
+        return list;
+    }
+
+    private boolean isFormatOk(String email) {
+        if (!SIMPLE_EMAIL.matcher(email).matches()) {
+            return false;
+        }
+        try {
+            InternetAddress address = new InternetAddress(email, true);
+            address.validate();
+            return StringUtils.hasText(address.getAddress());
+        } catch (AddressException e) {
+            return false;
+        }
+    }
+
+    private static String extractDomain(String email) {
+        int at = email.lastIndexOf('@');
+        if (at < 0 || at == email.length() - 1) {
+            return null;
+        }
+        return email.substring(at + 1).trim().toLowerCase(Locale.ROOT);
+    }
+
+    /**
+     * 域名是否具备收信能力:有 MX,或无 MX 但有 A/AAAA。
+     */
+    private boolean hasMailExchanger(String domain) {
+        CacheEntry cached = domainCache.get(domain);
+        long now = System.currentTimeMillis();
+        if (cached != null && cached.expireAt > now) {
+            return cached.ok;
+        }
+        boolean ok = lookupDnsMailCapable(domain);
+        domainCache.put(domain, new CacheEntry(ok, now + Math.max(60, domainCacheSeconds) * 1000L));
+        return ok;
+    }
+
+    private boolean lookupDnsMailCapable(String domain) {
+        DirContext ctx = null;
+        try {
+            Hashtable<String, String> env = new Hashtable<>();
+            env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
+            // 缩短 DNS 等待,避免发信接口长时间卡住
+            env.put("com.sun.jndi.dns.timeout.initial", "2000");
+            env.put("com.sun.jndi.dns.timeout.retries", "2");
+            ctx = new InitialDirContext(env);
+
+            Attributes mxAttrs = ctx.getAttributes(domain, new String[]{"MX"});
+            Attribute mx = mxAttrs == null ? null : mxAttrs.get("MX");
+            if (mx != null && mx.size() > 0) {
+                NamingEnumeration<?> all = mx.getAll();
+                while (all != null && all.hasMore()) {
+                    Object v = all.next();
+                    if (v != null && StringUtils.hasText(String.valueOf(v))) {
+                        return true;
+                    }
+                }
+            }
+
+            Attributes aAttrs = ctx.getAttributes(domain, new String[]{"A", "AAAA"});
+            if (aAttrs != null) {
+                Attribute a = aAttrs.get("A");
+                if (a != null && a.size() > 0) {
+                    return true;
+                }
+                Attribute aaaa = aAttrs.get("AAAA");
+                if (aaaa != null && aaaa.size() > 0) {
+                    return true;
+                }
+            }
+            return false;
+        } catch (NamingException e) {
+            log.warn("email domain dns lookup fail, domain={}, msg={}", domain, e.getMessage());
+            // DNS 异常时不直接判死(避免网络抖动误杀);视为域名检查未通过但可配置策略
+            return false;
+        } finally {
+            if (ctx != null) {
+                try {
+                    ctx.close();
+                } catch (NamingException ignored) {
+                    // ignore
+                }
+            }
+        }
+    }
+
+    private static final class CacheEntry {
+        private final boolean ok;
+        private final long expireAt;
+
+        private CacheEntry(boolean ok, long expireAt) {
+            this.ok = ok;
+            this.expireAt = expireAt;
+        }
+    }
+}

+ 3 - 0
storlead-mail/storlead-mail-common/src/main/java/com/storlead/sales/mail/common/service/impl/MailAccountBizServiceImpl.java

@@ -153,6 +153,9 @@ public class MailAccountBizServiceImpl implements MailAccountBizService {
         if (entity.getEnableReceive() == null) {
             entity.setEnableReceive(MailSceneEnum.isMkt(entity.getScene()) ? 0 : 1);
         }
+        if (entity.getEnableSend() == null) {
+            entity.setEnableSend(1);
+        }
 
         boolean ok = smtpPopSettingsService.saveOrUpdate(entity);
         if (Integer.valueOf(1).equals(entity.getUseDefault()) && ok) {

+ 75 - 0
storlead-mail/storlead-mail-common/src/main/java/com/storlead/sales/mail/common/service/impl/SystemConfigItemServiceImpl.java

@@ -0,0 +1,75 @@
+package com.storlead.sales.mail.common.service.impl;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
+import com.storlead.framework.common.constant.CommonConstant;
+import com.storlead.framework.mybatis.service.impl.MyBaseServiceImpl;
+import com.storlead.sales.mail.common.entity.SystemConfigItemEntity;
+import com.storlead.sales.mail.common.mapper.SystemConfigItemMapper;
+import com.storlead.sales.mail.common.service.SystemConfigItemService;
+import lombok.extern.log4j.Log4j2;
+import org.springframework.stereotype.Service;
+import org.springframework.util.StringUtils;
+
+import java.util.Date;
+
+@Log4j2
+@Service
+public class SystemConfigItemServiceImpl
+        extends MyBaseServiceImpl<SystemConfigItemMapper, SystemConfigItemEntity>
+        implements SystemConfigItemService {
+
+    @Override
+    public String getValue(String configKey) {
+        if (!StringUtils.hasText(configKey)) {
+            return null;
+        }
+        SystemConfigItemEntity entity = this.getOne(new LambdaQueryWrapper<SystemConfigItemEntity>()
+                .eq(SystemConfigItemEntity::getConfigKey, configKey)
+                .eq(SystemConfigItemEntity::getIsDelete, CommonConstant.DEL_FLAG_0)
+                .last("limit 1"));
+        return entity == null ? null : entity.getConfigValue();
+    }
+
+    @Override
+    public Integer getIntValue(String configKey, Integer defaultValue) {
+        String raw = getValue(configKey);
+        if (!StringUtils.hasText(raw)) {
+            return defaultValue;
+        }
+        try {
+            return Integer.parseInt(raw.trim());
+        } catch (NumberFormatException e) {
+            log.warn("system_config_item invalid int, key={}, value={}", configKey, raw);
+            return defaultValue;
+        }
+    }
+
+    @Override
+    public void setValue(String configKey, String configValue) {
+        if (!StringUtils.hasText(configKey)) {
+            return;
+        }
+        SystemConfigItemEntity existing = this.getOne(new LambdaQueryWrapper<SystemConfigItemEntity>()
+                .eq(SystemConfigItemEntity::getConfigKey, configKey)
+                .eq(SystemConfigItemEntity::getIsDelete, CommonConstant.DEL_FLAG_0)
+                .last("limit 1"));
+        Date now = new Date();
+        if (existing == null) {
+            SystemConfigItemEntity entity = new SystemConfigItemEntity();
+            entity.setConfigKey(configKey);
+            entity.setConfigValue(configValue);
+            entity.setIsDelete(CommonConstant.DEL_FLAG_0);
+            entity.setEnabled(Boolean.TRUE);
+            entity.setCreateTime(now);
+            entity.setUpdateTime(now);
+            this.save(entity);
+            return;
+        }
+        LambdaUpdateWrapper<SystemConfigItemEntity> update = new LambdaUpdateWrapper<>();
+        update.eq(SystemConfigItemEntity::getId, existing.getId());
+        update.set(SystemConfigItemEntity::getConfigValue, configValue);
+        update.set(SystemConfigItemEntity::getUpdateTime, now);
+        this.update(update);
+    }
+}

+ 2 - 0
storlead-mail/storlead-mail-common/src/main/resources/mapper/SmtpPopSettingsMapper.xml

@@ -29,6 +29,8 @@
             <result column="org_id" property="orgId" />
             <result column="daily_send_limit" property="dailySendLimit" />
             <result column="enable_receive" property="enableReceive" />
+            <result column="enable_send" property="enableSend" />
+            <result column="send_disable_reason" property="sendDisableReason" />
         </resultMap>
 
         <!-- 通用查询结果列 -->

+ 7 - 0
storlead-mail/storlead-mail-common/src/main/resources/sql/smtp_pop_settings_drop_temp_disable.sql

@@ -0,0 +1,7 @@
+-- 去掉临时隔离字段(若已存在);改为 enable_send + send_disable_reason 人工确认模式
+ALTER TABLE smtp_pop_settings
+    DROP COLUMN send_fail_streak,
+    DROP COLUMN send_disabled_until;
+
+ALTER TABLE smtp_pop_settings
+    ADD COLUMN send_disable_reason varchar(512) NULL COMMENT '不可发送原因;enable_send=0 时填写' AFTER enable_send;

+ 36 - 0
storlead-mail/storlead-mail-common/src/main/resources/sql/system_config_item_and_account_health.sql

@@ -0,0 +1,36 @@
+-- 1) 账号发信开关 + 不可用原因(若列已存在可跳过对应语句)
+ALTER TABLE smtp_pop_settings
+    ADD COLUMN enable_send tinyint NOT NULL DEFAULT 1 COMMENT '是否允许发信:1是 0否;账号级故障置0需人工确认' AFTER enable_receive,
+    ADD COLUMN send_disable_reason varchar(512) NULL COMMENT '不可发送原因;enable_send=0 时填写' AFTER enable_send;
+
+-- 若曾加过临时隔离字段,可手工清理:
+-- ALTER TABLE smtp_pop_settings DROP COLUMN send_fail_streak, DROP COLUMN send_disabled_until;
+
+-- 2) 系统变量配置表
+CREATE TABLE IF NOT EXISTS system_config_item (
+    id           bigint       NOT NULL AUTO_INCREMENT COMMENT '主键',
+    config_key   varchar(64)  NOT NULL COMMENT '配置键',
+    config_value varchar(512) NULL COMMENT '配置值',
+    remark       varchar(255) NULL COMMENT '说明',
+    owner_by     bigint       NULL COMMENT '数据归属人',
+    create_by    bigint       NULL COMMENT '创建人',
+    update_by    bigint       NULL COMMENT '最后更新人',
+    create_time  datetime     NULL COMMENT '创建时间',
+    update_time  datetime     NULL COMMENT '更新时间',
+    is_delete    tinyint      NOT NULL DEFAULT 0 COMMENT '逻辑删除:0未删除;1已删除',
+    enabled      tinyint      NOT NULL DEFAULT 1 COMMENT '是否启用:1启用;0禁用',
+    sort         int          NULL COMMENT '排序号',
+    PRIMARY KEY (id),
+    UNIQUE KEY uk_system_config_item_key (config_key)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='系统变量配置';
+
+-- 营销全站日发送限额 & 当日剩余(启动/零点任务用;运行时以 Redis 为准)
+INSERT INTO system_config_item (config_key, config_value, remark, is_delete, enabled, create_time, update_time)
+VALUES
+    ('mkt.daily.send.limit', '1000', '营销邮件当天发送限额(全站所有营销邮箱共用)', 0, 1, NOW(), NOW()),
+    ('mkt.daily.send.remaining', '1000', '营销邮件当天剩余发送额度', 0, 1, NOW(), NOW())
+ON DUPLICATE KEY UPDATE update_time = NOW();
+
+-- 若曾创建旧表可手工清理:
+-- DROP TABLE IF EXISTS mail_sys_config;
+-- DROP TABLE IF EXISTS mkt_send_quota_day;

+ 38 - 0
storlead-mail/storlead-mail-dispatch/src/main/java/com/storlead/sales/mail/dispatch/MktSendQuotaResetJob.java

@@ -0,0 +1,38 @@
+package com.storlead.sales.mail.dispatch;
+
+import com.storlead.sales.mail.mkt.service.MktSendQuotaService;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.scheduling.annotation.Scheduled;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.Resource;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * 每天零点:将系统变量剩余额度重置为当日限额,并重新加载到 Redis。
+ */
+@Slf4j
+@Component
+public class MktSendQuotaResetJob {
+
+    private final AtomicBoolean running = new AtomicBoolean(false);
+
+    @Resource
+    private MktSendQuotaService mktSendQuotaService;
+
+    @Scheduled(cron = "${storlead.mail.mkt.quota-reset-cron:0 0 0 * * ?}")
+    public void resetDailyQuota() {
+        if (!running.compareAndSet(false, true)) {
+            log.warn("mkt quota reset job still running, skip");
+            return;
+        }
+        try {
+            mktSendQuotaService.resetDailyRemainingFromLimit();
+            log.info("mkt daily send quota reset done");
+        } catch (Exception e) {
+            log.error("mkt daily send quota reset error", e);
+        } finally {
+            running.set(false);
+        }
+    }
+}

+ 26 - 0
storlead-mail/storlead-mail-mkt/src/main/java/com/storlead/sales/mail/mkt/config/MktMailSendProperties.java

@@ -0,0 +1,26 @@
+package com.storlead.sales.mail.mkt.config;
+
+import lombok.Data;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.stereotype.Component;
+
+/**
+ * 营销即时发信配置(账号轮询等)。
+ * 日发送限额改由 system_config_item + Redis 管理,见 MktSendQuotaService。
+ * 对应 application.yml:storlead.mail.mkt.*
+ */
+@Data
+@Component
+@ConfigurationProperties(prefix = "storlead.mail.mkt")
+public class MktMailSendProperties {
+
+    /**
+     * 同步发信时,首选账号失败后额外换号重试次数(总尝试=1+本值)。异步发信不换号重试。
+     */
+    private int sendAccountRetry = 2;
+
+    /**
+     * 每天零点重置剩余额度的 cron(也可在 application.yml 覆盖)。
+     */
+    private String quotaResetCron = "0 0 0 * * ?";
+}

+ 31 - 0
storlead-mail/storlead-mail-mkt/src/main/java/com/storlead/sales/mail/mkt/config/MktSendQuotaBootstrap.java

@@ -0,0 +1,31 @@
+package com.storlead.sales.mail.mkt.config;
+
+import com.storlead.sales.mail.mkt.service.MktSendQuotaService;
+import lombok.extern.log4j.Log4j2;
+import org.springframework.boot.ApplicationArguments;
+import org.springframework.boot.ApplicationRunner;
+import org.springframework.core.annotation.Order;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.Resource;
+
+/**
+ * 启动时:若 Redis 无营销剩余额度,则从系统变量 remaining 加载。
+ */
+@Log4j2
+@Component
+@Order(100)
+public class MktSendQuotaBootstrap implements ApplicationRunner {
+
+    @Resource
+    private MktSendQuotaService mktSendQuotaService;
+
+    @Override
+    public void run(ApplicationArguments args) {
+        try {
+            mktSendQuotaService.loadRemainingToRedisIfAbsent();
+        } catch (Exception e) {
+            log.error("mkt send quota bootstrap failed", e);
+        }
+    }
+}

+ 2 - 0
storlead-mail/storlead-mail-mkt/src/main/java/com/storlead/sales/mail/mkt/receive/MktMailReceivePersist.java

@@ -180,6 +180,8 @@ public class MktMailReceivePersist implements MailReceivePersistSpi {
             // 退信不当客户回复绑定
             if (!bounceMail) {
                 bindReply(account.getId(), message, draft, entity);
+            } else {
+
             }
 
             if (mktMailMessageService.save(entity)) {

+ 20 - 0
storlead-mail/storlead-mail-mkt/src/main/java/com/storlead/sales/mail/mkt/service/MktSendAccountHealthService.java

@@ -0,0 +1,20 @@
+package com.storlead.sales.mail.mkt.service;
+
+import com.storlead.sales.mail.common.entity.SmtpPopSettingsEntity;
+
+/**
+ * 营销发信账号可用性:选号过滤 enable_send;
+ * 登录失败 / 封号 / 风控等账号级问题标记不可发送并记录原因,需人工确认后恢复。
+ */
+public interface MktSendAccountHealthService {
+
+    /** 未删除且 enable_send≠0。 */
+    boolean isSendable(SmtpPopSettingsEntity account);
+
+    /**
+     * 判定是否账号级不可用(登录/封号/风控等);是则 enable_send=0 并写入原因。
+     *
+     * @param failReason SMTP/异常原文,用于归类与落库
+     */
+    void disableIfAccountIssue(Long accountId, String failReason);
+}

+ 25 - 0
storlead-mail/storlead-mail-mkt/src/main/java/com/storlead/sales/mail/mkt/service/MktSendAccountSelector.java

@@ -0,0 +1,25 @@
+package com.storlead.sales.mail.mkt.service;
+
+import com.storlead.sales.mail.common.entity.SmtpPopSettingsEntity;
+
+import java.util.List;
+import java.util.Set;
+
+/**
+ * 营销发信账号轮询选号:同池可用号中选,坏号跳过,避免单邮箱故障拖死整批。
+ */
+public interface MktSendAccountSelector {
+
+    /**
+     * 列出同池候选(已过滤 enable_send=0 / 删除)。
+     * 池:有 org → 同组织 MKT;无 org → 同 owner 个人 MKT。
+     */
+    List<SmtpPopSettingsEntity> listPoolCandidates(SmtpPopSettingsEntity preferred);
+
+    /**
+     * 选择下一个可用账号:优先 preferred(若健康且未排除),否则按今日成功量升序轮询。
+     *
+     * @param excludedAccountIds 本请求内已失败/不可用的账号(同步换号重试用)
+     */
+    SmtpPopSettingsEntity selectNext(SmtpPopSettingsEntity preferred, Set<Long> excludedAccountIds);
+}

+ 53 - 0
storlead-mail/storlead-mail-mkt/src/main/java/com/storlead/sales/mail/mkt/service/MktSendQuotaService.java

@@ -0,0 +1,53 @@
+package com.storlead.sales.mail.mkt.service;
+
+/**
+ * 营销发信全站日额度(系统变量 + Redis)。
+ * <p>
+ * 配置表:system_config_item(limit / remaining);运行时以 Redis 剩余额度为准。<br>
+ * 流程:tryReserve(Redis-1)→ bindReservation → 成功 confirm(落库剩余)/ 失败 rollback(Redis+1)。
+ * 延时发送不参与。
+ */
+public interface MktSendQuotaService {
+
+    /**
+     * 启动或 Redis 为空时:从系统变量 remaining 加载到 Redis。
+     */
+    void loadRemainingToRedisIfAbsent();
+
+    /**
+     * 强制用指定剩余值覆盖 Redis(零点重置后调用)。
+     */
+    void reloadRemainingToRedis(int remaining);
+
+    /**
+     * 零点任务:remaining = limit,写回配置表并刷新 Redis。
+     */
+    void resetDailyRemainingFromLimit();
+
+    /**
+     * 发前扣减 Redis 剩余;为 0 则失败。
+     *
+     * @return false 表示今日额度已用完
+     */
+    boolean tryReserve();
+
+    /**
+     * 预占成功后绑定 mailId,供 SMTP 回调确认/回滚。
+     */
+    void bindReservation(Long mailId);
+
+    /**
+     * SMTP 成功:预占生效,同步配置表 remaining。
+     */
+    void confirmByMailId(Long mailId);
+
+    /**
+     * SMTP/准备失败:Redis 剩余 +1,并同步配置表。
+     */
+    void rollbackByMailId(Long mailId);
+
+    /**
+     * 已 DECR 但尚未 bindReservation 时回补(选号/落库异常等)。
+     */
+    void rollbackUnbound();
+}

+ 151 - 23
storlead-mail/storlead-mail-mkt/src/main/java/com/storlead/sales/mail/mkt/service/impl/MktMailMessageServiceImpl.java

@@ -13,6 +13,8 @@ import com.storlead.sales.mail.common.entity.SmtpPopSettingsEntity;
 import com.storlead.sales.mail.common.enums.MailSceneEnum;
 import com.storlead.sales.mail.common.enums.MailSendStatus;
 import com.storlead.sales.mail.common.properties.MailFileProperties;
+import com.storlead.sales.mail.common.pojo.EmailAddressValidateResult;
+import com.storlead.sales.mail.common.service.EmailAddressValidateService;
 import com.storlead.sales.mail.common.service.MailAccountBizService;
 import com.storlead.sales.mail.common.service.MailTempAttachmentService;
 import com.storlead.sales.mail.common.transport.MailTransportSupport;
@@ -28,11 +30,14 @@ import com.storlead.sales.mail.mkt.pojo.MktMailQueryDTO;
 import com.storlead.sales.mail.mkt.pojo.MktOpenStatsVO;
 import com.storlead.sales.mail.mkt.pojo.MktSendMailDTO;
 import com.storlead.sales.mail.mkt.pojo.MktSendMailResult;
+import com.storlead.sales.mail.mkt.config.MktMailSendProperties;
 import com.storlead.sales.mail.mkt.service.MktMailAttachmentService;
 import com.storlead.sales.mail.mkt.service.MktMailBlacklistService;
 import com.storlead.sales.mail.mkt.service.MktMailMessageService;
 import com.storlead.sales.mail.mkt.service.MktMailReplyRecordService;
 import com.storlead.sales.mail.mkt.service.MktMailStatusService;
+import com.storlead.sales.mail.mkt.service.MktSendAccountSelector;
+import com.storlead.sales.mail.mkt.service.MktSendQuotaService;
 import com.storlead.sales.mail.mkt.support.MktMailHeaders;
 import com.storlead.sales.mail.mkt.util.MktMailSender;
 import lombok.extern.log4j.Log4j2;
@@ -63,8 +68,10 @@ import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.Date;
+import java.util.HashSet;
 import java.util.List;
 import java.util.Objects;
+import java.util.Set;
 import java.util.UUID;
 import java.util.concurrent.CompletableFuture;
 import java.util.stream.Collectors;
@@ -106,6 +113,18 @@ public class MktMailMessageServiceImpl extends MyBaseServiceImpl<MktMailMessageM
     @Resource
     private MktMailBlacklistService mktMailBlacklistService;
 
+    @Resource
+    private EmailAddressValidateService emailAddressValidateService;
+
+    @Resource
+    private MktSendQuotaService mktSendQuotaService;
+
+    @Resource
+    private MktSendAccountSelector mktSendAccountSelector;
+
+    @Resource
+    private MktMailSendProperties mktMailSendProperties;
+
     @Resource
     private MailFileProperties mailFileProperties;
 
@@ -171,21 +190,37 @@ public class MktMailMessageServiceImpl extends MyBaseServiceImpl<MktMailMessageM
         if (!StringUtils.hasText(dto.getSubject())) {
             throw new WebException("主题不能为空");
         }
+//        // 发信前校验主收件人:格式 + 域名收信能力,降低退信
+//        EmailAddressValidateResult recipientCheck = emailAddressValidateService.validate(dto.getRecipient());
+//        if (!recipientCheck.isValid()) {
+//            throw new WebException(StringUtils.hasText(recipientCheck.getReason())
+//                    ? recipientCheck.getReason() : "收件邮箱无效");
+//        }
+        dto.setRecipient(dto.getRecipient());
+        // 抄送/密送去掉明显无效地址
+        if (!CollectionUtils.isEmpty(dto.getRecipientCcList())) {
+            dto.setRecipientCcList(retainValidEmails(dto.getRecipientCcList()));
+        }
+        if (!CollectionUtils.isEmpty(dto.getRecipientBccList())) {
+            dto.setRecipientBccList(retainValidEmails(dto.getRecipientBccList()));
+        }
 
-        SmtpPopSettingsEntity account = mailAccountBizService.requireAccount(dto.getAccountId(), MailSceneEnum.MKT);
+        // preferred:调用方指定的首选发信号;实际发出账号可能因轮询切换而不同
+        SmtpPopSettingsEntity preferred = mailAccountBizService.requireAccount(dto.getAccountId(), MailSceneEnum.MKT);
 
         MktMailMessageEntity entity = resolveWritableEntity(dto.getId(), operatorId);
-        fillMessageFields(entity, dto, account, operatorId);
-        ensureTrackToken(entity, dto.getIsTrack());
-        assertTrackReady(entity);
-        // 主收件人在黑名单则整封不发;抄送/密送里的黑名单地址剔除后再发
-        applyRecipientBlacklist(entity, false);
-
+        /*
+         * 延时发送:产品约定不计入池级日限额、不参与账号轮询;
+         * 仅落库 status=DELAY,到期任务另议(本需求不改造延时链路)。
+         */
         boolean delayed = dto.getDelaySendTime() != null && dto.getDelaySendTime().after(new Date());
-        entity.setFolder(MktMailFolderEnum.SENTING.code);
-        entity.setInOutMark(2);
         if (delayed) {
-            // 延时尚未投递,正文需先落库供到期任务使用
+            fillMessageFields(entity, dto, preferred, operatorId);
+            ensureTrackToken(entity, dto.getIsTrack());
+            assertTrackReady(entity);
+            applyRecipientBlacklist(entity, false);
+            entity.setFolder(MktMailFolderEnum.SENTING.code);
+            entity.setInOutMark(2);
             entity.setStatus(STATUS_DELAY);
             entity.setDelaySendTime(dto.getDelaySendTime());
             this.saveOrUpdate(entity);
@@ -195,24 +230,85 @@ public class MktMailMessageServiceImpl extends MyBaseServiceImpl<MktMailMessageM
             return toSendResult(null, entity);
         }
 
-        entity.setStatus(STATUS_SENDING);
-        entity.setDelaySendTime(null);
-        this.saveOrUpdate(entity);
-        mktMailStatusService.ensureStatus(entity);
-        bindTempAttachments(entity.getId(), dto.getFileIds(), operatorId);
-        copyFormalToTemp(entity.getId(), dto.getOldFileIds(), operatorId);
-
-        SmtpPopSettingsEntity decrypted = decryptAccount(account);
+        /*
+         * 即时发送主流程(全站日限额 Redis + 账号轮询):
+         * 1) tryReserve:Redis 剩余额度 -1,为 0 则今日额度用完
+         * 2) selectNext 选健康号 → 落库 SENTING → bindReservation(mailId)
+         * 3) SMTP 成功 confirm(同步 DB remaining)/ 失败 rollback(Redis+1)
+         * 4) 同步可换号重试;异步只发一枪
+         */
+        Set<Long> excluded = new HashSet<>();
+        MailSendStatus lastStatus = MailSendStatus.FAILED;
+        int maxAttempts = 1 + Math.max(0, mktMailSendProperties.getSendAccountRetry());
         boolean async = Boolean.TRUE.equals(dto.getAsync());
-        MailSendStatus status = dispatchSmtpSend(entity.getId(), decrypted, async, entity.getContent());
+
+        for (int attempt = 0; attempt < maxAttempts; attempt++) {
+            // 每轮单独预占:上一轮失败时 Sender 已 rollback,需重新占额再试
+            if (!mktSendQuotaService.tryReserve()) {
+                throw new WebException("营销邮件今日发送额度已满");
+            }
+            // reserved=true:已 DECR 但尚未 bind,异常时需 rollbackByMailId 无法命中,用临时标记回补
+            boolean reserved = true;
+            Long reservedMailId = null;
+            try {
+                SmtpPopSettingsEntity account = mktSendAccountSelector.selectNext(preferred, excluded);
+                if (account == null) {
+                    throw new WebException("暂无可用的营销发信邮箱");
+                }
+                fillMessageFields(entity, dto, account, operatorId);
+                ensureTrackToken(entity, dto.getIsTrack());
+                assertTrackReady(entity);
+                applyRecipientBlacklist(entity, false);
+
+                entity.setFolder(MktMailFolderEnum.SENTING.code);
+                entity.setInOutMark(2);
+                entity.setStatus(STATUS_SENDING);
+                entity.setDelaySendTime(null);
+                entity.setFailReason(null);
+                this.saveOrUpdate(entity);
+                mktMailStatusService.ensureStatus(entity);
+                if (attempt == 0) {
+                    bindTempAttachments(entity.getId(), dto.getFileIds(), operatorId);
+                    copyFormalToTemp(entity.getId(), dto.getOldFileIds(), operatorId);
+                }
+
+                mktSendQuotaService.bindReservation(entity.getId());
+                reservedMailId = entity.getId();
+                reserved = false;
+
+                SmtpPopSettingsEntity decrypted = decryptAccount(account);
+                if (async) {
+                    dispatchSmtpSend(entity.getId(), decrypted, true, entity.getContent());
+                    MktMailMessageEntity latestAsync = this.getById(entity.getId());
+                    return toSendResult(null, latestAsync == null ? entity : latestAsync);
+                }
+
+                lastStatus = dispatchSmtpSend(entity.getId(), decrypted, false, entity.getContent());
+                if (lastStatus == MailSendStatus.SUCCESS || lastStatus == MailSendStatus.PARTIAL_SUCCESS) {
+                    break;
+                }
+                excluded.add(account.getId());
+                log.warn("mkt send attempt fail, mailId={}, accountId={}, status={}, tryNext={}",
+                        entity.getId(), account.getId(), lastStatus, attempt + 1 < maxAttempts);
+            } catch (RuntimeException ex) {
+                if (reserved) {
+                    // 已 DECR 未 bind:直接 Redis +1
+                    mktSendQuotaService.rollbackUnbound();
+                } else if (reservedMailId != null) {
+                    mktSendQuotaService.rollbackByMailId(reservedMailId);
+                }
+                throw ex;
+            }
+            if (reserved) {
+                mktSendQuotaService.rollbackUnbound();
+            }
+        }
+
         MktMailMessageEntity latest = this.getById(entity.getId());
         if (latest == null) {
             latest = entity;
         }
-        if (async) {
-            return toSendResult(null, latest);
-        }
-        return toSendResult(status, latest);
+        return toSendResult(lastStatus, latest);
     }
 
     /**
@@ -226,6 +322,9 @@ public class MktMailMessageServiceImpl extends MyBaseServiceImpl<MktMailMessageM
         mktMailBlacklistService.assertRecipientsNotBlacklisted(to);
         String cc = emptyIfNull(mktMailBlacklistService.retainDeliverable(entity.getRecipientCc()));
         String bcc = emptyIfNull(mktMailBlacklistService.retainDeliverable(entity.getRecipientBcc()));
+        // 再过滤格式/域名无效地址,进一步降低退信
+        cc = emptyIfNull(emailAddressValidateService.retainDeliverable(cc));
+        bcc = emptyIfNull(emailAddressValidateService.retainDeliverable(bcc));
         String oldCc = emptyIfNull(entity.getRecipientCc());
         String oldBcc = emptyIfNull(entity.getRecipientBcc());
         entity.setRecipientCc(StringUtils.hasText(cc) ? cc : "");
@@ -240,6 +339,26 @@ public class MktMailMessageServiceImpl extends MyBaseServiceImpl<MktMailMessageM
         this.update(update);
     }
 
+    private List<String> retainValidEmails(List<String> emails) {
+        if (CollectionUtils.isEmpty(emails)) {
+            return emails;
+        }
+        List<String> kept = new ArrayList<>();
+        for (String email : emails) {
+            if (!StringUtils.hasText(email)) {
+                continue;
+            }
+            try {
+                emailAddressValidateService.assertDeliverable(email.trim());
+                kept.add(email.trim());
+            } catch (WebException ex) {
+                log.info("mkt drop invalid cc/bcc before send, email={}, reason={}",
+                        email, ex.getMessage());
+            }
+        }
+        return kept;
+    }
+
     private static String emptyIfNull(String value) {
         return value == null ? "" : value;
     }
@@ -650,6 +769,9 @@ public class MktMailMessageServiceImpl extends MyBaseServiceImpl<MktMailMessageM
         }
     }
 
+    /**
+     * SMTP 准备阶段失败(建连前异常等):落失败态并释放已预占池额度。
+     */
     private void markSendingFailed(Long mailId, String reason) {
         LambdaUpdateWrapper<MktMailMessageEntity> fail = new LambdaUpdateWrapper<>();
         fail.eq(MktMailMessageEntity::getId, mailId);
@@ -658,6 +780,12 @@ public class MktMailMessageServiceImpl extends MyBaseServiceImpl<MktMailMessageM
         fail.set(MktMailMessageEntity::getFailReason, reason);
         this.update(fail);
         mktMailStatusService.markSendStatus(mailId, STATUS_FAIL);
+        // 准备失败不会进 Sender 回调,需在此主动回滚预占
+        try {
+            mktSendQuotaService.rollbackByMailId(mailId);
+        } catch (Exception e) {
+            log.error("mkt quota rollback on prepare fail error, mailId={}", mailId, e);
+        }
     }
 
     private MimeMessage buildMimeMessage(Session session,

+ 72 - 26
storlead-mail/storlead-mail-mkt/src/main/java/com/storlead/sales/mail/mkt/service/impl/MktMailStatusServiceImpl.java

@@ -45,28 +45,7 @@ public class MktMailStatusServiceImpl extends MyBaseServiceImpl<MktMailStatusMap
 
         MktMailStatusEntity existing = getByMailId(mail.getId());
         if (existing != null) {
-            LambdaUpdateWrapper<MktMailStatusEntity> patch = new LambdaUpdateWrapper<>();
-            patch.eq(MktMailStatusEntity::getMailId, mail.getId());
-            patch.eq(MktMailStatusEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
-            boolean needPatch = false;
-            if (mail.getStatus() != null && !mail.getStatus().equals(existing.getSendStatus())) {
-                patch.set(MktMailStatusEntity::getSendStatus, mail.getStatus());
-                needPatch = true;
-            }
-            if (existing.getOutboxId() == null && outboxId != null) {
-                patch.set(MktMailStatusEntity::getOutboxId, outboxId);
-                needPatch = true;
-            }
-            if (!StringUtils.hasText(existing.getOutbox()) && StringUtils.hasText(outbox)) {
-                patch.set(MktMailStatusEntity::getOutbox, outbox);
-                needPatch = true;
-            }
-            if (needPatch) {
-                Date now = new Date();
-                patch.set(MktMailStatusEntity::getStatusUpdatedAt, now);
-                patch.set(MktMailStatusEntity::getUpdateTime, now);
-                this.update(patch);
-            }
+            patchOutboxAndSendStatus(existing, mail.getStatus(), outboxId, outbox);
             return;
         }
 
@@ -92,7 +71,12 @@ public class MktMailStatusServiceImpl extends MyBaseServiceImpl<MktMailStatusMap
         try {
             this.save(row);
         } catch (DuplicateKeyException e) {
-            log.debug("mkt_mail_status already exists, mailId={}", mail.getId());
+            // 并发下另一线程已建行:必须再补丁 outbox,否则可能留下无 outbox 的行且不再刷新 status_updated_at
+            log.debug("mkt_mail_status already exists, retry patch, mailId={}", mail.getId());
+            MktMailStatusEntity again = getByMailId(mail.getId());
+            if (again != null) {
+                patchOutboxAndSendStatus(again, mail.getStatus(), outboxId, outbox);
+            }
         } catch (Exception e) {
             log.error("ensureStatus error, mailId={}", mail.getId(), e);
         }
@@ -104,11 +88,21 @@ public class MktMailStatusServiceImpl extends MyBaseServiceImpl<MktMailStatusMap
             return;
         }
         ensureMinimalRow(mailId);
+        MktMailStatusEntity existing = getByMailId(mailId);
+        MktMailMessageEntity mail = mktMailMessageMapper.selectById(mailId);
         Date now = new Date();
         LambdaUpdateWrapper<MktMailStatusEntity> update = new LambdaUpdateWrapper<>();
         update.eq(MktMailStatusEntity::getMailId, mailId);
         update.eq(MktMailStatusEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
         update.set(MktMailStatusEntity::getSendStatus, sendStatus);
+        // 发送态变更时若 outbox 仍为空,一并补齐并刷新 status_updated_at,避免业务已 synced 后永远拉不到 outbox_id
+        if (existing != null && existing.getOutboxId() == null && mail != null && mail.getAccountId() != null) {
+            update.set(MktMailStatusEntity::getOutboxId, mail.getAccountId());
+            update.set(MktMailStatusEntity::getOutbox,
+                    resolveOutboxAddr(mail.getFromAddr(), mail.getAccountId()));
+            log.info("mkt_mail_status backfill outbox on markSendStatus, mailId={}, outboxId={}",
+                    mailId, mail.getAccountId());
+        }
         update.set(MktMailStatusEntity::getStatusUpdatedAt, now);
         update.set(MktMailStatusEntity::getUpdateTime, now);
         this.update(update);
@@ -252,14 +246,61 @@ public class MktMailStatusServiceImpl extends MyBaseServiceImpl<MktMailStatusMap
                 .last("limit 1"));
     }
 
+    /**
+     * 已存在行时补齐 outbox / sendStatus,并刷新 status_updated_at(驱动业务增量同步)。
+     */
+    private void patchOutboxAndSendStatus(MktMailStatusEntity existing,
+                                          Integer sendStatus,
+                                          Long outboxId,
+                                          String outbox) {
+        if (existing == null || existing.getMailId() == null) {
+            return;
+        }
+        LambdaUpdateWrapper<MktMailStatusEntity> patch = new LambdaUpdateWrapper<>();
+        patch.eq(MktMailStatusEntity::getMailId, existing.getMailId());
+        patch.eq(MktMailStatusEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
+        boolean needPatch = false;
+        if (sendStatus != null && !sendStatus.equals(existing.getSendStatus())) {
+            patch.set(MktMailStatusEntity::getSendStatus, sendStatus);
+            needPatch = true;
+        }
+        // outbox 为空才补;若账号轮询换号且需覆盖,应另开逻辑并同样刷新 status_updated_at
+        if (existing.getOutboxId() == null && outboxId != null) {
+            patch.set(MktMailStatusEntity::getOutboxId, outboxId);
+            patch.set(MktMailStatusEntity::getOutbox, outbox);
+            needPatch = true;
+        } else if (existing.getOutboxId() != null && outboxId != null
+                && !existing.getOutboxId().equals(outboxId)) {
+            // 发信号已切换:覆盖 outbox,必须刷新水位,否则业务侧一直是旧/空值
+            patch.set(MktMailStatusEntity::getOutboxId, outboxId);
+            patch.set(MktMailStatusEntity::getOutbox, outbox);
+            needPatch = true;
+        }
+        if (!needPatch) {
+            return;
+        }
+        Date now = new Date();
+        patch.set(MktMailStatusEntity::getStatusUpdatedAt, now);
+        patch.set(MktMailStatusEntity::getUpdateTime, now);
+        this.update(patch);
+        log.info("mkt_mail_status patched outbox/sendStatus, mailId={}, outboxId={}, sendStatus={}",
+                existing.getMailId(), outboxId, sendStatus);
+    }
+
     /**
      * 兜底建行:从原信补齐 outbox_id / outbox。
+     * 行已存在但 outbox 为空时也会回填并刷新 status_updated_at。
      */
     private void ensureMinimalRow(Long mailId) {
-        if (getByMailId(mailId) != null) {
+        MktMailStatusEntity existing = getByMailId(mailId);
+        MktMailMessageEntity mail = mktMailMessageMapper.selectById(mailId);
+        if (existing != null) {
+            if (existing.getOutboxId() == null && mail != null && mail.getAccountId() != null) {
+                patchOutboxAndSendStatus(existing, null, mail.getAccountId(),
+                        resolveOutboxAddr(mail.getFromAddr(), mail.getAccountId()));
+            }
             return;
         }
-        MktMailMessageEntity mail = mktMailMessageMapper.selectById(mailId);
         Date now = new Date();
         MktMailStatusEntity row = new MktMailStatusEntity();
         row.setMailId(mailId);
@@ -286,7 +327,12 @@ public class MktMailStatusServiceImpl extends MyBaseServiceImpl<MktMailStatusMap
         try {
             this.save(row);
         } catch (DuplicateKeyException ignore) {
-            // concurrent insert
+            // concurrent insert:再尝试补 outbox
+            MktMailStatusEntity again = getByMailId(mailId);
+            if (again != null && again.getOutboxId() == null && mail != null && mail.getAccountId() != null) {
+                patchOutboxAndSendStatus(again, null, mail.getAccountId(),
+                        resolveOutboxAddr(mail.getFromAddr(), mail.getAccountId()));
+            }
         } catch (Exception e) {
             log.error("ensureMinimalRow error, mailId={}", mailId, e);
         }

+ 107 - 0
storlead-mail/storlead-mail-mkt/src/main/java/com/storlead/sales/mail/mkt/service/impl/MktSendAccountHealthServiceImpl.java

@@ -0,0 +1,107 @@
+package com.storlead.sales.mail.mkt.service.impl;
+
+import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
+import com.storlead.framework.common.constant.CommonConstant;
+import com.storlead.sales.mail.common.entity.SmtpPopSettingsEntity;
+import com.storlead.sales.mail.common.service.SmtpPopSettingsService;
+import com.storlead.sales.mail.mkt.service.MktSendAccountHealthService;
+import lombok.extern.log4j.Log4j2;
+import org.springframework.stereotype.Service;
+import org.springframework.util.StringUtils;
+
+import javax.annotation.Resource;
+import java.util.Locale;
+
+/**
+ * 营销发信账号可用性。
+ * <p>
+ * 登录失败、封号、风控等:置 enable_send=0 并写 send_disable_reason,需人工确认后才能再发。<br>
+ * 普通投递失败(如收件人拒收)不关停账号。
+ */
+@Log4j2
+@Service
+public class MktSendAccountHealthServiceImpl implements MktSendAccountHealthService {
+
+    @Resource
+    private SmtpPopSettingsService smtpPopSettingsService;
+
+    @Override
+    public boolean isSendable(SmtpPopSettingsEntity account) {
+        if (account == null || !Integer.valueOf(CommonConstant.DEL_FLAG_0).equals(account.getIsDelete())) {
+            return false;
+        }
+        // null 视为允许发信(存量未刷字段时兼容)
+        return account.getEnableSend() == null || account.getEnableSend() != 0;
+    }
+
+    @Override
+    public void disableIfAccountIssue(Long accountId, String failReason) {
+        if (accountId == null) {
+            return;
+        }
+        String reason = classifyAccountIssue(failReason);
+        if (reason == null) {
+            return;
+        }
+        String stored = truncate(reason, 500);
+        LambdaUpdateWrapper<SmtpPopSettingsEntity> update = new LambdaUpdateWrapper<>();
+        update.eq(SmtpPopSettingsEntity::getId, accountId);
+        update.set(SmtpPopSettingsEntity::getEnableSend, 0);
+        update.set(SmtpPopSettingsEntity::getSendDisableReason, stored);
+        smtpPopSettingsService.update(update);
+        log.warn("mkt account marked unsendable, need manual confirm, accountId={}, reason={}",
+                accountId, stored);
+    }
+
+    /**
+     * @return 归类后的不可用原因;非账号级问题返回 null(不关停)
+     */
+    static String classifyAccountIssue(String failReason) {
+        if (!StringUtils.hasText(failReason)) {
+            return null;
+        }
+        String raw = failReason.trim();
+        String lower = raw.toLowerCase(Locale.ROOT);
+
+        // 登录 / 认证
+        if (containsAny(lower,
+                "authenticationfailed", "authentication failed", "auth fail",
+                "login fail", "login failed", "invalid credentials", "bad credentials",
+                "username and password not accepted", "535",
+                "登录失败", "认证失败", "密码错误", "账号或密码", "用户名或密码")) {
+            return "登录/认证失败: " + raw;
+        }
+        // 封号 / 停用
+        if (containsAny(lower,
+                "account disabled", "account suspended", "account locked", "mailbox disabled",
+                "user disabled", "account closed", "blocked account",
+                "封号", "账号被封", "帐号被封", "账号停用", "账户停用", "已被停用", "禁止登录")) {
+            return "账号封禁/停用: " + raw;
+        }
+        // 风控 / 限制发送
+        if (containsAny(lower,
+                "risk control", "riskcontrol", "spam", "blocked for spam",
+                "sending denied", "relay access denied", "policy rejection",
+                "too many", "rate limit", "quota exceeded", "daily sending limit",
+                "风控", "风险控制", "限制发送", "发送受限", "反垃圾", "涉嫌垃圾", "频率过高", "发送超限")) {
+            return "风控/发送受限: " + raw;
+        }
+        return null;
+    }
+
+    private static boolean containsAny(String text, String... keywords) {
+        for (String k : keywords) {
+            if (text.contains(k)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    private static String truncate(String value, int max) {
+        if (value == null || value.length() <= max) {
+            return value;
+        }
+        return value.substring(0, max);
+    }
+}

+ 144 - 0
storlead-mail/storlead-mail-mkt/src/main/java/com/storlead/sales/mail/mkt/service/impl/MktSendAccountSelectorImpl.java

@@ -0,0 +1,144 @@
+package com.storlead.sales.mail.mkt.service.impl;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.storlead.framework.common.constant.CommonConstant;
+import com.storlead.sales.mail.common.entity.SmtpPopSettingsEntity;
+import com.storlead.sales.mail.common.enums.MailSceneEnum;
+import com.storlead.sales.mail.common.service.MailAccountBizService;
+import com.storlead.sales.mail.mkt.entity.MktMailMessageEntity;
+import com.storlead.sales.mail.mkt.mapper.MktMailMessageMapper;
+import com.storlead.sales.mail.mkt.service.MktSendAccountHealthService;
+import com.storlead.sales.mail.mkt.service.MktSendAccountSelector;
+import lombok.extern.log4j.Log4j2;
+import org.springframework.stereotype.Service;
+import org.springframework.util.CollectionUtils;
+
+import javax.annotation.Resource;
+import java.time.LocalDate;
+import java.time.ZoneId;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * 营销发信账号轮询选号。
+ * <p>
+ * 池范围:有 orgId → 同组织全部 MKT 号;无 org → 同 owner 的个人 MKT 号。<br>
+ * 目的:enable_send=0 的坏号跳过,换池内其他可用号,避免整批发信卡死。
+ */
+@Log4j2
+@Service
+public class MktSendAccountSelectorImpl implements MktSendAccountSelector {
+
+    private static final ZoneId ZONE = ZoneId.of("Asia/Shanghai");
+    private static final int STATUS_SUCCESS = 1;
+
+    @Resource
+    private MailAccountBizService mailAccountBizService;
+
+    @Resource
+    private MktSendAccountHealthService mktSendAccountHealthService;
+
+    @Resource
+    private MktMailMessageMapper mktMailMessageMapper;
+
+    /**
+     * 列出池内当前可发账号(已过滤删除 / 停用发信 / 临时隔离)。
+     */
+    @Override
+    public List<SmtpPopSettingsEntity> listPoolCandidates(SmtpPopSettingsEntity preferred) {
+        if (preferred == null) {
+            return new ArrayList<>();
+        }
+        List<SmtpPopSettingsEntity> pool;
+        if (preferred.getOrgId() != null) {
+            // 组织池:同 org 下所有 scene=MKT 账号共用日额度与轮询
+            pool = mailAccountBizService.listOrgAccounts(preferred.getOrgId(), MailSceneEnum.MKT.getCode());
+        } else {
+            // 无组织:退化为该用户名下个人 MKT 账号池
+            pool = mailAccountBizService.listAccounts(preferred.getOwnerBy(), MailSceneEnum.MKT.getCode());
+        }
+        if (CollectionUtils.isEmpty(pool)) {
+            // 池为空时至少保留首选(若健康)
+            pool = new ArrayList<>();
+            pool.add(preferred);
+        }
+        return pool.stream()
+                .filter(mktSendAccountHealthService::isSendable)
+                .collect(Collectors.toList());
+    }
+
+    /**
+     * 选下一个发信号:
+     * 1) 首选账号仍健康且未在本轮排除列表 → 继续用首选(From 尽量不变);
+     * 2) 否则按「今日成功封数升序」选最闲的号,实现简单负载均衡。
+     *
+     * @param excludedAccountIds 本请求内已失败的账号,同步换号重试时传入
+     */
+    @Override
+    public SmtpPopSettingsEntity selectNext(SmtpPopSettingsEntity preferred, Set<Long> excludedAccountIds) {
+        Set<Long> excluded = excludedAccountIds == null ? new HashSet<>() : excludedAccountIds;
+        List<SmtpPopSettingsEntity> candidates = listPoolCandidates(preferred).stream()
+                .filter(a -> a.getId() != null && !excluded.contains(a.getId()))
+                .collect(Collectors.toList());
+        if (candidates.isEmpty()) {
+            return null;
+        }
+        // 首选仍健康且未排除 → 优先用首选(保持 From 稳定)
+        if (preferred != null && preferred.getId() != null
+                && !excluded.contains(preferred.getId())
+                && mktSendAccountHealthService.isSendable(preferred)) {
+            for (SmtpPopSettingsEntity c : candidates) {
+                if (Objects.equals(c.getId(), preferred.getId())) {
+                    return c;
+                }
+            }
+        }
+        // 轮询:今日已成功越少越优先,相同则 id 小者优先
+        Map<Long, Long> todaySuccess = loadTodaySuccessCount(candidates);
+        candidates.sort(Comparator
+                .comparingLong((SmtpPopSettingsEntity a) -> todaySuccess.getOrDefault(a.getId(), 0L))
+                .thenComparing(SmtpPopSettingsEntity::getId, Comparator.nullsLast(Long::compareTo)));
+        SmtpPopSettingsEntity picked = candidates.get(0);
+        log.info("mkt select send account, preferredId={}, pickedId={}, poolSize={}",
+                preferred == null ? null : preferred.getId(), picked.getId(), candidates.size());
+        return picked;
+    }
+
+    /** 统计候选账号今日 SMTP 成功封数,供轮询排序。 */
+    private Map<Long, Long> loadTodaySuccessCount(List<SmtpPopSettingsEntity> candidates) {
+        Map<Long, Long> result = new HashMap<>();
+        if (CollectionUtils.isEmpty(candidates)) {
+            return result;
+        }
+        List<Long> ids = candidates.stream().map(SmtpPopSettingsEntity::getId).filter(Objects::nonNull)
+                .collect(Collectors.toList());
+        if (ids.isEmpty()) {
+            return result;
+        }
+        Date dayStart = Date.from(LocalDate.now(ZONE).atStartOfDay(ZONE).toInstant());
+        List<MktMailMessageEntity> rows = mktMailMessageMapper.selectList(new LambdaQueryWrapper<MktMailMessageEntity>()
+                .select(MktMailMessageEntity::getId, MktMailMessageEntity::getAccountId)
+                .in(MktMailMessageEntity::getAccountId, ids)
+                .eq(MktMailMessageEntity::getStatus, STATUS_SUCCESS)
+                .eq(MktMailMessageEntity::getIsDelete, CommonConstant.DEL_FLAG_0)
+                .ge(MktMailMessageEntity::getSentTime, dayStart));
+        if (CollectionUtils.isEmpty(rows)) {
+            return result;
+        }
+        for (MktMailMessageEntity row : rows) {
+            if (row.getAccountId() == null) {
+                continue;
+            }
+            result.merge(row.getAccountId(), 1L, Long::sum);
+        }
+        return result;
+    }
+}

+ 154 - 0
storlead-mail/storlead-mail-mkt/src/main/java/com/storlead/sales/mail/mkt/service/impl/MktSendQuotaServiceImpl.java

@@ -0,0 +1,154 @@
+package com.storlead.sales.mail.mkt.service.impl;
+
+import com.storlead.framework.common.constant.RedisKeySaltConstant;
+import com.storlead.sales.mail.common.entity.SystemConfigItemEntity;
+import com.storlead.sales.mail.common.service.SystemConfigItemService;
+import com.storlead.sales.mail.mkt.service.MktSendQuotaService;
+import lombok.extern.log4j.Log4j2;
+import org.redisson.api.RAtomicLong;
+import org.redisson.api.RedissonClient;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * 营销全站日额度:系统变量存 limit/remaining,运行时用 Redisson 原子计数加减。
+ * <ul>
+ *   <li>启动:Redis 无 key → 从 remaining 加载</li>
+ *   <li>发信:原子 -1;结果 &lt; 0 则回加并拒绝(阈值为 0 表示用完)</li>
+ *   <li>成功:同步 DB remaining;失败:+1 并同步 DB</li>
+ *   <li>零点:remaining = limit,写 DB 并 reload Redis</li>
+ * </ul>
+ */
+@Log4j2
+@Service
+public class MktSendQuotaServiceImpl implements MktSendQuotaService {
+
+    private static final String REDIS_KEY = RedisKeySaltConstant.MKT_DAILY_SEND_REMAINING;
+
+    /** 已扣减 Redis、等待 SMTP 结果的 mailId */
+    private final Set<Long> pendingMailIds = ConcurrentHashMap.newKeySet();
+
+    @Resource
+    private RedissonClient redissonClient;
+
+    @Resource
+    private SystemConfigItemService systemConfigItemService;
+
+    @Override
+    public void loadRemainingToRedisIfAbsent() {
+        RAtomicLong counter = counter();
+        if (counter.isExists()) {
+            log.info("mkt send quota redis already present, key={}, value={}", REDIS_KEY, counter.get());
+            return;
+        }
+        int remaining = resolveRemainingFromDb();
+        counter.set(remaining);
+        log.info("mkt send quota loaded from config to redis, remaining={}", remaining);
+    }
+
+    @Override
+    public void reloadRemainingToRedis(int remaining) {
+        int value = Math.max(0, remaining);
+        counter().set(value);
+        log.info("mkt send quota redis reloaded, remaining={}", value);
+    }
+
+    @Override
+    public void resetDailyRemainingFromLimit() {
+        int limit = resolveLimitFromDb();
+        systemConfigItemService.setValue(SystemConfigItemEntity.KEY_MKT_DAILY_SEND_REMAINING, String.valueOf(limit));
+        reloadRemainingToRedis(limit);
+        log.info("mkt daily send remaining reset from limit={}", limit);
+    }
+
+    /**
+     * 原子 DECR;key 不存在时先从配置加载。
+     * 扣完后若 &lt; 0,说明已用尽,INCR 回滚并返回 false。
+     */
+    @Override
+    public boolean tryReserve() {
+        ensureRedisPresent();
+        long after = counter().decrementAndGet();
+        if (after < 0) {
+            counter().incrementAndGet();
+            log.warn("mkt daily send quota exhausted, redisAfter={}", after);
+            return false;
+        }
+        log.info("mkt quota reserved, remainingAfter={}", after);
+        return true;
+    }
+
+    @Override
+    public void bindReservation(Long mailId) {
+        if (mailId != null) {
+            pendingMailIds.add(mailId);
+        }
+    }
+
+    @Override
+    public void confirmByMailId(Long mailId) {
+        if (mailId == null || !pendingMailIds.remove(mailId)) {
+            return;
+        }
+        // 成功:额度已在 tryReserve 扣过,同步当前剩余到配置表
+        syncRemainingToDb();
+    }
+
+    @Override
+    public void rollbackByMailId(Long mailId) {
+        if (mailId == null || !pendingMailIds.remove(mailId)) {
+            return;
+        }
+        doIncrementRemaining("mailId=" + mailId);
+    }
+
+    @Override
+    public void rollbackUnbound() {
+        doIncrementRemaining("unbound");
+    }
+
+    private void doIncrementRemaining(String reason) {
+        ensureRedisPresent();
+        long after = counter().incrementAndGet();
+        log.info("mkt quota rolled back, reason={}, remainingAfter={}", reason, after);
+        syncRemainingToDb();
+    }
+
+    private void ensureRedisPresent() {
+        if (!counter().isExists()) {
+            loadRemainingToRedisIfAbsent();
+        }
+    }
+
+    private void syncRemainingToDb() {
+        try {
+            long remaining = Math.max(0, counter().get());
+            systemConfigItemService.setValue(
+                    SystemConfigItemEntity.KEY_MKT_DAILY_SEND_REMAINING, String.valueOf(remaining));
+        } catch (Exception e) {
+            log.error("mkt sync remaining to db error", e);
+        }
+    }
+
+    private RAtomicLong counter() {
+        return redissonClient.getAtomicLong(REDIS_KEY);
+    }
+
+    private int resolveLimitFromDb() {
+        Integer limit = systemConfigItemService.getIntValue(
+                SystemConfigItemEntity.KEY_MKT_DAILY_SEND_LIMIT, 0);
+        return limit == null || limit < 0 ? 0 : limit;
+    }
+
+    private int resolveRemainingFromDb() {
+        Integer remaining = systemConfigItemService.getIntValue(
+                SystemConfigItemEntity.KEY_MKT_DAILY_SEND_REMAINING, null);
+        if (remaining != null && remaining >= 0) {
+            return remaining;
+        }
+        return resolveLimitFromDb();
+    }
+}

+ 34 - 1
storlead-mail/storlead-mail-mkt/src/main/java/com/storlead/sales/mail/mkt/util/MktMailSender.java

@@ -15,6 +15,8 @@ import com.storlead.sales.mail.mkt.service.MktMailAttachmentService;
 import com.storlead.sales.mail.mkt.service.MktMailBlacklistService;
 import com.storlead.sales.mail.mkt.service.MktMailMessageService;
 import com.storlead.sales.mail.mkt.service.MktMailStatusService;
+import com.storlead.sales.mail.mkt.service.MktSendAccountHealthService;
+import com.storlead.sales.mail.mkt.service.MktSendQuotaService;
 import lombok.extern.log4j.Log4j2;
 import org.springframework.beans.factory.ObjectProvider;
 import org.springframework.context.annotation.Lazy;
@@ -67,6 +69,12 @@ public class MktMailSender {
     @Resource
     private MktMailBlacklistService mktMailBlacklistService;
 
+    @Resource
+    private MktSendQuotaService mktSendQuotaService;
+
+    @Resource
+    private MktSendAccountHealthService mktSendAccountHealthService;
+
     private final List<MktMailSendCallback> sendCallbacks;
 
     public MktMailSender(ObjectProvider<MktMailSendCallback> callbackProvider) {
@@ -142,12 +150,13 @@ public class MktMailSender {
             }
         } catch (SendFailedException e) {
             log.error("mkt SendFailedException, mailId={}", mail == null ? null : mail.getId(), e);
+            // 收件拒收等一般不关停账号;若文案含封号/风控关键词仍会标记不可发送
             onEmailSentFailure(mail, e.getMessage());
             blacklistOn550(mail, e);
             completeQuietly(future, MailSendStatus.SERVER_EXCEPTION_550);
         } catch (AuthenticationFailedException e) {
             log.error("mkt AuthenticationFailedException, mailId={}", mail == null ? null : mail.getId(), e);
-            onEmailSentFailure(mail, e.getMessage());
+            onEmailSentFailure(mail, "AuthenticationFailedException: " + e.getMessage());
             completeQuietly(future, MailSendStatus.SERVER_LOGIN_FAIL);
         } catch (MessagingException e) {
             log.error("mkt MessagingException, mailId={}", mail == null ? null : mail.getId(), e);
@@ -171,6 +180,9 @@ public class MktMailSender {
     }
 
     /**
+     * SMTP 投递成功落库(CAS:仅 status=SENDING 可改为成功,防 listener 与兜底重复回调)。
+     * 首次成功时同步日额度 remaining。账号 enable_send 不自动恢复(需人工确认)。
+     *
      * @return true 表示本次首次落成功态(可触发业务回调)
      */
     private boolean markDelivered(MktMailMessageEntity entity, String messageId, boolean partial) {
@@ -207,6 +219,12 @@ public class MktMailSender {
             } catch (Exception ex) {
                 log.error("mkt_mail_status markSendStatus success error, mailId={}", entity.getId(), ex);
             }
+            // Redis 已在 tryReserve 扣过;此处同步 system_config_item.remaining
+            try {
+                mktSendQuotaService.confirmByMailId(entity.getId());
+            } catch (Exception ex) {
+                log.error("mkt quota confirm error, mailId={}", entity.getId(), ex);
+            }
             return true;
         } catch (Exception e) {
             log.error("mkt markDelivered error, mailId={}, partial={}", entity.getId(), partial, e);
@@ -214,6 +232,10 @@ public class MktMailSender {
         }
     }
 
+    /**
+     * SMTP 失败落库(CAS:仅 SENDING→FAIL)。
+     * 回滚日额度;若为登录/封号/风控等账号问题则 enable_send=0 并写原因,需人工确认。
+     */
     private void onEmailSentFailure(MktMailMessageEntity entity, String reason) {
         if (entity == null || entity.getId() == null) {
             return;
@@ -236,6 +258,17 @@ public class MktMailSender {
             } catch (Exception ex) {
                 log.error("mkt_mail_status markSendStatus fail error, mailId={}", entity.getId(), ex);
             }
+            try {
+                mktSendQuotaService.rollbackByMailId(entity.getId());
+            } catch (Exception ex) {
+                log.error("mkt quota rollback error, mailId={}", entity.getId(), ex);
+            }
+            // 账号级问题:关停发信并记原因;普通失败不关停
+            try {
+                mktSendAccountHealthService.disableIfAccountIssue(entity.getAccountId(), failReason);
+            } catch (Exception ex) {
+                log.error("mkt account disable check error, accountId={}", entity.getAccountId(), ex);
+            }
             fireFailure(entity, failReason);
         } catch (Exception e) {
             log.error("mkt onEmailSentFailure error, mailId={}", entity.getId(), e);