修复:检测无效的 SMTP DNS 解析
This commit is contained in:
+33
@@ -10,6 +10,8 @@ import javax.mail.Session;
|
||||
import javax.mail.Transport;
|
||||
import javax.mail.internet.InternetAddress;
|
||||
import javax.mail.internet.MimeMessage;
|
||||
import java.net.Inet4Address;
|
||||
import java.net.InetAddress;
|
||||
import java.util.Properties;
|
||||
|
||||
@Service
|
||||
@@ -37,6 +39,7 @@ public class SmtpEmailChannelProvider implements EmailChannelProvider {
|
||||
@Override
|
||||
public void send(ManagedChannelConfig channelConfig, String to, String subject, String content) {
|
||||
validate(channelConfig);
|
||||
validateResolvedHost(channelConfig);
|
||||
requireText(to, "收件人不能为空");
|
||||
requireText(subject, "测试邮件主题不能为空");
|
||||
requireText(content, "测试邮件内容不能为空");
|
||||
@@ -57,6 +60,7 @@ public class SmtpEmailChannelProvider implements EmailChannelProvider {
|
||||
public ChannelHealthCheckResult checkHealth(ManagedChannelConfig channelConfig) {
|
||||
try {
|
||||
validate(channelConfig);
|
||||
validateResolvedHost(channelConfig);
|
||||
Session session = buildSession(channelConfig);
|
||||
Transport transport = session.getTransport("smtp");
|
||||
transport.connect(
|
||||
@@ -123,4 +127,33 @@ public class SmtpEmailChannelProvider implements EmailChannelProvider {
|
||||
+ " 请改成 SSL=开启、STARTTLS=关闭。");
|
||||
}
|
||||
}
|
||||
|
||||
private void validateResolvedHost(ManagedChannelConfig channelConfig) {
|
||||
String host = channelConfig.getStringConfig("host");
|
||||
try {
|
||||
InetAddress[] addresses = InetAddress.getAllByName(host);
|
||||
for (InetAddress address : addresses) {
|
||||
if (isSuspiciousBenchmarkAddress(address)) {
|
||||
throw new IllegalArgumentException("SMTP 主机解析异常:"
|
||||
+ host + " 当前被解析为 " + address.getHostAddress()
|
||||
+ ",这不是正常的公网 SMTP 地址。请检查本机 DNS、代理或网络环境后再重试。");
|
||||
}
|
||||
}
|
||||
} catch (IllegalArgumentException exception) {
|
||||
throw exception;
|
||||
} catch (Exception exception) {
|
||||
throw new IllegalArgumentException("SMTP 主机解析失败: " + host + ",请检查 DNS 或网络环境。", exception);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isSuspiciousBenchmarkAddress(InetAddress address) {
|
||||
if (!(address instanceof Inet4Address inet4Address)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
byte[] bytes = inet4Address.getAddress();
|
||||
int first = Byte.toUnsignedInt(bytes[0]);
|
||||
int second = Byte.toUnsignedInt(bytes[1]);
|
||||
return first == 198 && (second == 18 || second == 19);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,6 +104,7 @@
|
||||
- `STARTTLS` 和 `SSL` 同时启用
|
||||
- `587` 端口错误开启 `SSL`
|
||||
- `465` 端口错误开启 `STARTTLS`
|
||||
- 如果 `smtp.gmail.com` 之类的主机被异常解析到 `198.18.x.x` 这类保留地址,会直接返回 DNS/网络异常提示
|
||||
- 后台页面补充 Gmail / QQ 邮箱配置说明
|
||||
- 健康检查失败时会优先返回中文可操作提示,降低排障成本
|
||||
|
||||
|
||||
Reference in New Issue
Block a user