MailGuard

Struct MailGuard 

Source
pub struct MailGuard { /* private fields */ }
Expand description

主要的邮箱检测器

Implementations§

Source§

impl MailGuard

Source

pub fn new() -> Self

创建新的检测器实例

Source

pub fn with_config(config: MailGuardConfig) -> Self

使用自定义配置创建检测器

Examples found in repository?
examples/advanced_usage.rs (line 21)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7    tracing_subscriber::fmt()
8        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
9        .init();
10
11    println!("🔍 MailGuard-RS Advanced Example");
12    println!("=================================");
13
14    // Create detector with custom configuration
15    let config = MailGuardConfig {
16        dns_timeout: Duration::from_secs(3),
17        enable_cache: true,
18        cache_ttl: Duration::from_secs(600), // 10-minute cache
19    };
20
21    let detector = MailGuard::with_config(config);
22
23    // Test a series of email addresses
24    let test_cases = vec![
25        (
26            "正常邮箱",
27            vec!["user@example.com", "test@google.com", "admin@microsoft.com"],
28        ),
29        (
30            "可疑域名",
31            vec![
32                "temp@tempmail.org",
33                "test@guerrillamail.com",
34                "user@mailinator.com",
35                "fake@10minutemail.com",
36            ],
37        ),
38        (
39            "无效格式",
40            vec![
41                "invalid-email",
42                "@missing-user.com",
43                "missing-domain@",
44                "double@@domain.com",
45            ],
46        ),
47    ];
48
49    for (category, emails) in test_cases {
50        println!("\n📂 {} ({} 个):", category, emails.len());
51        println!("{}", "-".repeat(50));
52
53        for email in emails {
54            match detector.check_email(email).await {
55                Ok(status) => {
56                    let threat_indicator = if status.is_threat { "⚠️ " } else { "✅" };
57                    let cache_indicator = if status.from_cache {
58                        " [缓存]"
59                    } else {
60                        " [查询]"
61                    };
62
63                    if let Some(threat_type) = &status.threat_type {
64                        println!(
65                            "  {} {} -> {} (等级: {}, 类型: {}){}",
66                            threat_indicator,
67                            email,
68                            threat_type.description(),
69                            threat_type.severity_level(),
70                            format!("{:?}", threat_type),
71                            cache_indicator
72                        );
73                    } else {
74                        println!(
75                            "  {} {} -> 安全{}",
76                            threat_indicator, email, cache_indicator
77                        );
78                    }
79                }
80                Err(e) => {
81                    println!("  ❌ {} -> 错误: {}", email, e);
82                }
83            }
84        }
85
86        // 显示当前缓存状态
87        if let Some(cache_size) = detector.cache_stats() {
88            println!("    💾 缓存条目: {}", cache_size);
89        }
90    }
91
92    // 演示威胁类型功能
93    println!("\n🎯 威胁类型详细信息:");
94    println!("===================");
95
96    let threat_types = vec![
97        ThreatType::Spam,
98        ThreatType::Phishing,
99        ThreatType::Malware,
100        ThreatType::Botnet,
101        ThreatType::Pup,
102        ThreatType::Unknown(42),
103    ];
104
105    for threat_type in threat_types {
106        println!(
107            "  {:?}: {} (等级: {})",
108            threat_type,
109            threat_type.description(),
110            threat_type.severity_level()
111        );
112    }
113
114    // 演示IP分类功能
115    println!("\n🔢 IP 分类示例:");
116    println!("================");
117
118    for octet in [2, 3, 4, 5, 6, 7, 9, 10, 11, 42, 255] {
119        let threat_type = ThreatType::from_ip_last_octet(octet);
120        println!(
121            "  127.0.0.{} -> {:?} ({})",
122            octet,
123            threat_type,
124            threat_type.description()
125        );
126    }
127
128    // 批量测试性能
129    println!("\n⚡ 批量处理性能测试:");
130    println!("=====================");
131
132    let batch_emails = vec![
133        "test1@example.com",
134        "test2@gmail.com",
135        "temp1@tempmail.org",
136        "temp2@guerrillamail.com",
137        "user@mailinator.com",
138    ];
139
140    let start = std::time::Instant::now();
141    let results = detector.check_emails_batch(&batch_emails).await;
142    let duration = start.elapsed();
143
144    println!("  处理 {} 个邮箱用时: {:?}", batch_emails.len(), duration);
145    println!("  平均每个邮箱: {:?}", duration / batch_emails.len() as u32);
146
147    let mut threats_found = 0;
148    let mut cache_hits = 0;
149    for result in &results {
150        if let Ok(status) = result {
151            if status.is_threat {
152                threats_found += 1;
153            }
154            if status.from_cache {
155                cache_hits += 1;
156            }
157        }
158    }
159
160    println!("  发现威胁: {} 个", threats_found);
161    println!("  缓存命中: {} 个", cache_hits);
162
163    // 缓存管理演示
164    println!("\n💾 缓存管理:");
165    println!("=============");
166
167    println!("  当前缓存大小: {:?}", detector.cache_stats());
168
169    // 清理过期条目
170    detector.cleanup_cache();
171    println!("  清理后缓存大小: {:?}", detector.cache_stats());
172
173    // 清空缓存
174    detector.clear_cache();
175    println!("  清空后缓存大小: {:?}", detector.cache_stats());
176
177    println!("\n✨ 示例完成!");
178    Ok(())
179}
Source

pub async fn check_email(&self, email: &str) -> Result<EmailStatus>

检查单个邮箱地址

Examples found in repository?
examples/advanced_usage.rs (line 54)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7    tracing_subscriber::fmt()
8        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
9        .init();
10
11    println!("🔍 MailGuard-RS Advanced Example");
12    println!("=================================");
13
14    // Create detector with custom configuration
15    let config = MailGuardConfig {
16        dns_timeout: Duration::from_secs(3),
17        enable_cache: true,
18        cache_ttl: Duration::from_secs(600), // 10-minute cache
19    };
20
21    let detector = MailGuard::with_config(config);
22
23    // Test a series of email addresses
24    let test_cases = vec![
25        (
26            "正常邮箱",
27            vec!["user@example.com", "test@google.com", "admin@microsoft.com"],
28        ),
29        (
30            "可疑域名",
31            vec![
32                "temp@tempmail.org",
33                "test@guerrillamail.com",
34                "user@mailinator.com",
35                "fake@10minutemail.com",
36            ],
37        ),
38        (
39            "无效格式",
40            vec![
41                "invalid-email",
42                "@missing-user.com",
43                "missing-domain@",
44                "double@@domain.com",
45            ],
46        ),
47    ];
48
49    for (category, emails) in test_cases {
50        println!("\n📂 {} ({} 个):", category, emails.len());
51        println!("{}", "-".repeat(50));
52
53        for email in emails {
54            match detector.check_email(email).await {
55                Ok(status) => {
56                    let threat_indicator = if status.is_threat { "⚠️ " } else { "✅" };
57                    let cache_indicator = if status.from_cache {
58                        " [缓存]"
59                    } else {
60                        " [查询]"
61                    };
62
63                    if let Some(threat_type) = &status.threat_type {
64                        println!(
65                            "  {} {} -> {} (等级: {}, 类型: {}){}",
66                            threat_indicator,
67                            email,
68                            threat_type.description(),
69                            threat_type.severity_level(),
70                            format!("{:?}", threat_type),
71                            cache_indicator
72                        );
73                    } else {
74                        println!(
75                            "  {} {} -> 安全{}",
76                            threat_indicator, email, cache_indicator
77                        );
78                    }
79                }
80                Err(e) => {
81                    println!("  ❌ {} -> 错误: {}", email, e);
82                }
83            }
84        }
85
86        // 显示当前缓存状态
87        if let Some(cache_size) = detector.cache_stats() {
88            println!("    💾 缓存条目: {}", cache_size);
89        }
90    }
91
92    // 演示威胁类型功能
93    println!("\n🎯 威胁类型详细信息:");
94    println!("===================");
95
96    let threat_types = vec![
97        ThreatType::Spam,
98        ThreatType::Phishing,
99        ThreatType::Malware,
100        ThreatType::Botnet,
101        ThreatType::Pup,
102        ThreatType::Unknown(42),
103    ];
104
105    for threat_type in threat_types {
106        println!(
107            "  {:?}: {} (等级: {})",
108            threat_type,
109            threat_type.description(),
110            threat_type.severity_level()
111        );
112    }
113
114    // 演示IP分类功能
115    println!("\n🔢 IP 分类示例:");
116    println!("================");
117
118    for octet in [2, 3, 4, 5, 6, 7, 9, 10, 11, 42, 255] {
119        let threat_type = ThreatType::from_ip_last_octet(octet);
120        println!(
121            "  127.0.0.{} -> {:?} ({})",
122            octet,
123            threat_type,
124            threat_type.description()
125        );
126    }
127
128    // 批量测试性能
129    println!("\n⚡ 批量处理性能测试:");
130    println!("=====================");
131
132    let batch_emails = vec![
133        "test1@example.com",
134        "test2@gmail.com",
135        "temp1@tempmail.org",
136        "temp2@guerrillamail.com",
137        "user@mailinator.com",
138    ];
139
140    let start = std::time::Instant::now();
141    let results = detector.check_emails_batch(&batch_emails).await;
142    let duration = start.elapsed();
143
144    println!("  处理 {} 个邮箱用时: {:?}", batch_emails.len(), duration);
145    println!("  平均每个邮箱: {:?}", duration / batch_emails.len() as u32);
146
147    let mut threats_found = 0;
148    let mut cache_hits = 0;
149    for result in &results {
150        if let Ok(status) = result {
151            if status.is_threat {
152                threats_found += 1;
153            }
154            if status.from_cache {
155                cache_hits += 1;
156            }
157        }
158    }
159
160    println!("  发现威胁: {} 个", threats_found);
161    println!("  缓存命中: {} 个", cache_hits);
162
163    // 缓存管理演示
164    println!("\n💾 缓存管理:");
165    println!("=============");
166
167    println!("  当前缓存大小: {:?}", detector.cache_stats());
168
169    // 清理过期条目
170    detector.cleanup_cache();
171    println!("  清理后缓存大小: {:?}", detector.cache_stats());
172
173    // 清空缓存
174    detector.clear_cache();
175    println!("  清空后缓存大小: {:?}", detector.cache_stats());
176
177    println!("\n✨ 示例完成!");
178    Ok(())
179}
Source

pub async fn check_domain(&self, domain: &str) -> Result<DomainStatus>

检查域名

Source

pub async fn check_emails_batch( &self, emails: &[&str], ) -> Vec<Result<EmailStatus>>

批量检查邮箱

Examples found in repository?
examples/advanced_usage.rs (line 141)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7    tracing_subscriber::fmt()
8        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
9        .init();
10
11    println!("🔍 MailGuard-RS Advanced Example");
12    println!("=================================");
13
14    // Create detector with custom configuration
15    let config = MailGuardConfig {
16        dns_timeout: Duration::from_secs(3),
17        enable_cache: true,
18        cache_ttl: Duration::from_secs(600), // 10-minute cache
19    };
20
21    let detector = MailGuard::with_config(config);
22
23    // Test a series of email addresses
24    let test_cases = vec![
25        (
26            "正常邮箱",
27            vec!["user@example.com", "test@google.com", "admin@microsoft.com"],
28        ),
29        (
30            "可疑域名",
31            vec![
32                "temp@tempmail.org",
33                "test@guerrillamail.com",
34                "user@mailinator.com",
35                "fake@10minutemail.com",
36            ],
37        ),
38        (
39            "无效格式",
40            vec![
41                "invalid-email",
42                "@missing-user.com",
43                "missing-domain@",
44                "double@@domain.com",
45            ],
46        ),
47    ];
48
49    for (category, emails) in test_cases {
50        println!("\n📂 {} ({} 个):", category, emails.len());
51        println!("{}", "-".repeat(50));
52
53        for email in emails {
54            match detector.check_email(email).await {
55                Ok(status) => {
56                    let threat_indicator = if status.is_threat { "⚠️ " } else { "✅" };
57                    let cache_indicator = if status.from_cache {
58                        " [缓存]"
59                    } else {
60                        " [查询]"
61                    };
62
63                    if let Some(threat_type) = &status.threat_type {
64                        println!(
65                            "  {} {} -> {} (等级: {}, 类型: {}){}",
66                            threat_indicator,
67                            email,
68                            threat_type.description(),
69                            threat_type.severity_level(),
70                            format!("{:?}", threat_type),
71                            cache_indicator
72                        );
73                    } else {
74                        println!(
75                            "  {} {} -> 安全{}",
76                            threat_indicator, email, cache_indicator
77                        );
78                    }
79                }
80                Err(e) => {
81                    println!("  ❌ {} -> 错误: {}", email, e);
82                }
83            }
84        }
85
86        // 显示当前缓存状态
87        if let Some(cache_size) = detector.cache_stats() {
88            println!("    💾 缓存条目: {}", cache_size);
89        }
90    }
91
92    // 演示威胁类型功能
93    println!("\n🎯 威胁类型详细信息:");
94    println!("===================");
95
96    let threat_types = vec![
97        ThreatType::Spam,
98        ThreatType::Phishing,
99        ThreatType::Malware,
100        ThreatType::Botnet,
101        ThreatType::Pup,
102        ThreatType::Unknown(42),
103    ];
104
105    for threat_type in threat_types {
106        println!(
107            "  {:?}: {} (等级: {})",
108            threat_type,
109            threat_type.description(),
110            threat_type.severity_level()
111        );
112    }
113
114    // 演示IP分类功能
115    println!("\n🔢 IP 分类示例:");
116    println!("================");
117
118    for octet in [2, 3, 4, 5, 6, 7, 9, 10, 11, 42, 255] {
119        let threat_type = ThreatType::from_ip_last_octet(octet);
120        println!(
121            "  127.0.0.{} -> {:?} ({})",
122            octet,
123            threat_type,
124            threat_type.description()
125        );
126    }
127
128    // 批量测试性能
129    println!("\n⚡ 批量处理性能测试:");
130    println!("=====================");
131
132    let batch_emails = vec![
133        "test1@example.com",
134        "test2@gmail.com",
135        "temp1@tempmail.org",
136        "temp2@guerrillamail.com",
137        "user@mailinator.com",
138    ];
139
140    let start = std::time::Instant::now();
141    let results = detector.check_emails_batch(&batch_emails).await;
142    let duration = start.elapsed();
143
144    println!("  处理 {} 个邮箱用时: {:?}", batch_emails.len(), duration);
145    println!("  平均每个邮箱: {:?}", duration / batch_emails.len() as u32);
146
147    let mut threats_found = 0;
148    let mut cache_hits = 0;
149    for result in &results {
150        if let Ok(status) = result {
151            if status.is_threat {
152                threats_found += 1;
153            }
154            if status.from_cache {
155                cache_hits += 1;
156            }
157        }
158    }
159
160    println!("  发现威胁: {} 个", threats_found);
161    println!("  缓存命中: {} 个", cache_hits);
162
163    // 缓存管理演示
164    println!("\n💾 缓存管理:");
165    println!("=============");
166
167    println!("  当前缓存大小: {:?}", detector.cache_stats());
168
169    // 清理过期条目
170    detector.cleanup_cache();
171    println!("  清理后缓存大小: {:?}", detector.cache_stats());
172
173    // 清空缓存
174    detector.clear_cache();
175    println!("  清空后缓存大小: {:?}", detector.cache_stats());
176
177    println!("\n✨ 示例完成!");
178    Ok(())
179}
Source

pub async fn check_domains_batch( &self, domains: &[&str], ) -> Vec<Result<DomainStatus>>

批量检查域名

Source

pub fn cleanup_cache(&self)

清理缓存中的过期条目

Examples found in repository?
examples/advanced_usage.rs (line 170)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7    tracing_subscriber::fmt()
8        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
9        .init();
10
11    println!("🔍 MailGuard-RS Advanced Example");
12    println!("=================================");
13
14    // Create detector with custom configuration
15    let config = MailGuardConfig {
16        dns_timeout: Duration::from_secs(3),
17        enable_cache: true,
18        cache_ttl: Duration::from_secs(600), // 10-minute cache
19    };
20
21    let detector = MailGuard::with_config(config);
22
23    // Test a series of email addresses
24    let test_cases = vec![
25        (
26            "正常邮箱",
27            vec!["user@example.com", "test@google.com", "admin@microsoft.com"],
28        ),
29        (
30            "可疑域名",
31            vec![
32                "temp@tempmail.org",
33                "test@guerrillamail.com",
34                "user@mailinator.com",
35                "fake@10minutemail.com",
36            ],
37        ),
38        (
39            "无效格式",
40            vec![
41                "invalid-email",
42                "@missing-user.com",
43                "missing-domain@",
44                "double@@domain.com",
45            ],
46        ),
47    ];
48
49    for (category, emails) in test_cases {
50        println!("\n📂 {} ({} 个):", category, emails.len());
51        println!("{}", "-".repeat(50));
52
53        for email in emails {
54            match detector.check_email(email).await {
55                Ok(status) => {
56                    let threat_indicator = if status.is_threat { "⚠️ " } else { "✅" };
57                    let cache_indicator = if status.from_cache {
58                        " [缓存]"
59                    } else {
60                        " [查询]"
61                    };
62
63                    if let Some(threat_type) = &status.threat_type {
64                        println!(
65                            "  {} {} -> {} (等级: {}, 类型: {}){}",
66                            threat_indicator,
67                            email,
68                            threat_type.description(),
69                            threat_type.severity_level(),
70                            format!("{:?}", threat_type),
71                            cache_indicator
72                        );
73                    } else {
74                        println!(
75                            "  {} {} -> 安全{}",
76                            threat_indicator, email, cache_indicator
77                        );
78                    }
79                }
80                Err(e) => {
81                    println!("  ❌ {} -> 错误: {}", email, e);
82                }
83            }
84        }
85
86        // 显示当前缓存状态
87        if let Some(cache_size) = detector.cache_stats() {
88            println!("    💾 缓存条目: {}", cache_size);
89        }
90    }
91
92    // 演示威胁类型功能
93    println!("\n🎯 威胁类型详细信息:");
94    println!("===================");
95
96    let threat_types = vec![
97        ThreatType::Spam,
98        ThreatType::Phishing,
99        ThreatType::Malware,
100        ThreatType::Botnet,
101        ThreatType::Pup,
102        ThreatType::Unknown(42),
103    ];
104
105    for threat_type in threat_types {
106        println!(
107            "  {:?}: {} (等级: {})",
108            threat_type,
109            threat_type.description(),
110            threat_type.severity_level()
111        );
112    }
113
114    // 演示IP分类功能
115    println!("\n🔢 IP 分类示例:");
116    println!("================");
117
118    for octet in [2, 3, 4, 5, 6, 7, 9, 10, 11, 42, 255] {
119        let threat_type = ThreatType::from_ip_last_octet(octet);
120        println!(
121            "  127.0.0.{} -> {:?} ({})",
122            octet,
123            threat_type,
124            threat_type.description()
125        );
126    }
127
128    // 批量测试性能
129    println!("\n⚡ 批量处理性能测试:");
130    println!("=====================");
131
132    let batch_emails = vec![
133        "test1@example.com",
134        "test2@gmail.com",
135        "temp1@tempmail.org",
136        "temp2@guerrillamail.com",
137        "user@mailinator.com",
138    ];
139
140    let start = std::time::Instant::now();
141    let results = detector.check_emails_batch(&batch_emails).await;
142    let duration = start.elapsed();
143
144    println!("  处理 {} 个邮箱用时: {:?}", batch_emails.len(), duration);
145    println!("  平均每个邮箱: {:?}", duration / batch_emails.len() as u32);
146
147    let mut threats_found = 0;
148    let mut cache_hits = 0;
149    for result in &results {
150        if let Ok(status) = result {
151            if status.is_threat {
152                threats_found += 1;
153            }
154            if status.from_cache {
155                cache_hits += 1;
156            }
157        }
158    }
159
160    println!("  发现威胁: {} 个", threats_found);
161    println!("  缓存命中: {} 个", cache_hits);
162
163    // 缓存管理演示
164    println!("\n💾 缓存管理:");
165    println!("=============");
166
167    println!("  当前缓存大小: {:?}", detector.cache_stats());
168
169    // 清理过期条目
170    detector.cleanup_cache();
171    println!("  清理后缓存大小: {:?}", detector.cache_stats());
172
173    // 清空缓存
174    detector.clear_cache();
175    println!("  清空后缓存大小: {:?}", detector.cache_stats());
176
177    println!("\n✨ 示例完成!");
178    Ok(())
179}
Source

pub fn cache_stats(&self) -> Option<usize>

获取缓存统计信息

Examples found in repository?
examples/advanced_usage.rs (line 87)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7    tracing_subscriber::fmt()
8        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
9        .init();
10
11    println!("🔍 MailGuard-RS Advanced Example");
12    println!("=================================");
13
14    // Create detector with custom configuration
15    let config = MailGuardConfig {
16        dns_timeout: Duration::from_secs(3),
17        enable_cache: true,
18        cache_ttl: Duration::from_secs(600), // 10-minute cache
19    };
20
21    let detector = MailGuard::with_config(config);
22
23    // Test a series of email addresses
24    let test_cases = vec![
25        (
26            "正常邮箱",
27            vec!["user@example.com", "test@google.com", "admin@microsoft.com"],
28        ),
29        (
30            "可疑域名",
31            vec![
32                "temp@tempmail.org",
33                "test@guerrillamail.com",
34                "user@mailinator.com",
35                "fake@10minutemail.com",
36            ],
37        ),
38        (
39            "无效格式",
40            vec![
41                "invalid-email",
42                "@missing-user.com",
43                "missing-domain@",
44                "double@@domain.com",
45            ],
46        ),
47    ];
48
49    for (category, emails) in test_cases {
50        println!("\n📂 {} ({} 个):", category, emails.len());
51        println!("{}", "-".repeat(50));
52
53        for email in emails {
54            match detector.check_email(email).await {
55                Ok(status) => {
56                    let threat_indicator = if status.is_threat { "⚠️ " } else { "✅" };
57                    let cache_indicator = if status.from_cache {
58                        " [缓存]"
59                    } else {
60                        " [查询]"
61                    };
62
63                    if let Some(threat_type) = &status.threat_type {
64                        println!(
65                            "  {} {} -> {} (等级: {}, 类型: {}){}",
66                            threat_indicator,
67                            email,
68                            threat_type.description(),
69                            threat_type.severity_level(),
70                            format!("{:?}", threat_type),
71                            cache_indicator
72                        );
73                    } else {
74                        println!(
75                            "  {} {} -> 安全{}",
76                            threat_indicator, email, cache_indicator
77                        );
78                    }
79                }
80                Err(e) => {
81                    println!("  ❌ {} -> 错误: {}", email, e);
82                }
83            }
84        }
85
86        // 显示当前缓存状态
87        if let Some(cache_size) = detector.cache_stats() {
88            println!("    💾 缓存条目: {}", cache_size);
89        }
90    }
91
92    // 演示威胁类型功能
93    println!("\n🎯 威胁类型详细信息:");
94    println!("===================");
95
96    let threat_types = vec![
97        ThreatType::Spam,
98        ThreatType::Phishing,
99        ThreatType::Malware,
100        ThreatType::Botnet,
101        ThreatType::Pup,
102        ThreatType::Unknown(42),
103    ];
104
105    for threat_type in threat_types {
106        println!(
107            "  {:?}: {} (等级: {})",
108            threat_type,
109            threat_type.description(),
110            threat_type.severity_level()
111        );
112    }
113
114    // 演示IP分类功能
115    println!("\n🔢 IP 分类示例:");
116    println!("================");
117
118    for octet in [2, 3, 4, 5, 6, 7, 9, 10, 11, 42, 255] {
119        let threat_type = ThreatType::from_ip_last_octet(octet);
120        println!(
121            "  127.0.0.{} -> {:?} ({})",
122            octet,
123            threat_type,
124            threat_type.description()
125        );
126    }
127
128    // 批量测试性能
129    println!("\n⚡ 批量处理性能测试:");
130    println!("=====================");
131
132    let batch_emails = vec![
133        "test1@example.com",
134        "test2@gmail.com",
135        "temp1@tempmail.org",
136        "temp2@guerrillamail.com",
137        "user@mailinator.com",
138    ];
139
140    let start = std::time::Instant::now();
141    let results = detector.check_emails_batch(&batch_emails).await;
142    let duration = start.elapsed();
143
144    println!("  处理 {} 个邮箱用时: {:?}", batch_emails.len(), duration);
145    println!("  平均每个邮箱: {:?}", duration / batch_emails.len() as u32);
146
147    let mut threats_found = 0;
148    let mut cache_hits = 0;
149    for result in &results {
150        if let Ok(status) = result {
151            if status.is_threat {
152                threats_found += 1;
153            }
154            if status.from_cache {
155                cache_hits += 1;
156            }
157        }
158    }
159
160    println!("  发现威胁: {} 个", threats_found);
161    println!("  缓存命中: {} 个", cache_hits);
162
163    // 缓存管理演示
164    println!("\n💾 缓存管理:");
165    println!("=============");
166
167    println!("  当前缓存大小: {:?}", detector.cache_stats());
168
169    // 清理过期条目
170    detector.cleanup_cache();
171    println!("  清理后缓存大小: {:?}", detector.cache_stats());
172
173    // 清空缓存
174    detector.clear_cache();
175    println!("  清空后缓存大小: {:?}", detector.cache_stats());
176
177    println!("\n✨ 示例完成!");
178    Ok(())
179}
Source

pub fn clear_cache(&self)

清空缓存

Examples found in repository?
examples/advanced_usage.rs (line 174)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7    tracing_subscriber::fmt()
8        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
9        .init();
10
11    println!("🔍 MailGuard-RS Advanced Example");
12    println!("=================================");
13
14    // Create detector with custom configuration
15    let config = MailGuardConfig {
16        dns_timeout: Duration::from_secs(3),
17        enable_cache: true,
18        cache_ttl: Duration::from_secs(600), // 10-minute cache
19    };
20
21    let detector = MailGuard::with_config(config);
22
23    // Test a series of email addresses
24    let test_cases = vec![
25        (
26            "正常邮箱",
27            vec!["user@example.com", "test@google.com", "admin@microsoft.com"],
28        ),
29        (
30            "可疑域名",
31            vec![
32                "temp@tempmail.org",
33                "test@guerrillamail.com",
34                "user@mailinator.com",
35                "fake@10minutemail.com",
36            ],
37        ),
38        (
39            "无效格式",
40            vec![
41                "invalid-email",
42                "@missing-user.com",
43                "missing-domain@",
44                "double@@domain.com",
45            ],
46        ),
47    ];
48
49    for (category, emails) in test_cases {
50        println!("\n📂 {} ({} 个):", category, emails.len());
51        println!("{}", "-".repeat(50));
52
53        for email in emails {
54            match detector.check_email(email).await {
55                Ok(status) => {
56                    let threat_indicator = if status.is_threat { "⚠️ " } else { "✅" };
57                    let cache_indicator = if status.from_cache {
58                        " [缓存]"
59                    } else {
60                        " [查询]"
61                    };
62
63                    if let Some(threat_type) = &status.threat_type {
64                        println!(
65                            "  {} {} -> {} (等级: {}, 类型: {}){}",
66                            threat_indicator,
67                            email,
68                            threat_type.description(),
69                            threat_type.severity_level(),
70                            format!("{:?}", threat_type),
71                            cache_indicator
72                        );
73                    } else {
74                        println!(
75                            "  {} {} -> 安全{}",
76                            threat_indicator, email, cache_indicator
77                        );
78                    }
79                }
80                Err(e) => {
81                    println!("  ❌ {} -> 错误: {}", email, e);
82                }
83            }
84        }
85
86        // 显示当前缓存状态
87        if let Some(cache_size) = detector.cache_stats() {
88            println!("    💾 缓存条目: {}", cache_size);
89        }
90    }
91
92    // 演示威胁类型功能
93    println!("\n🎯 威胁类型详细信息:");
94    println!("===================");
95
96    let threat_types = vec![
97        ThreatType::Spam,
98        ThreatType::Phishing,
99        ThreatType::Malware,
100        ThreatType::Botnet,
101        ThreatType::Pup,
102        ThreatType::Unknown(42),
103    ];
104
105    for threat_type in threat_types {
106        println!(
107            "  {:?}: {} (等级: {})",
108            threat_type,
109            threat_type.description(),
110            threat_type.severity_level()
111        );
112    }
113
114    // 演示IP分类功能
115    println!("\n🔢 IP 分类示例:");
116    println!("================");
117
118    for octet in [2, 3, 4, 5, 6, 7, 9, 10, 11, 42, 255] {
119        let threat_type = ThreatType::from_ip_last_octet(octet);
120        println!(
121            "  127.0.0.{} -> {:?} ({})",
122            octet,
123            threat_type,
124            threat_type.description()
125        );
126    }
127
128    // 批量测试性能
129    println!("\n⚡ 批量处理性能测试:");
130    println!("=====================");
131
132    let batch_emails = vec![
133        "test1@example.com",
134        "test2@gmail.com",
135        "temp1@tempmail.org",
136        "temp2@guerrillamail.com",
137        "user@mailinator.com",
138    ];
139
140    let start = std::time::Instant::now();
141    let results = detector.check_emails_batch(&batch_emails).await;
142    let duration = start.elapsed();
143
144    println!("  处理 {} 个邮箱用时: {:?}", batch_emails.len(), duration);
145    println!("  平均每个邮箱: {:?}", duration / batch_emails.len() as u32);
146
147    let mut threats_found = 0;
148    let mut cache_hits = 0;
149    for result in &results {
150        if let Ok(status) = result {
151            if status.is_threat {
152                threats_found += 1;
153            }
154            if status.from_cache {
155                cache_hits += 1;
156            }
157        }
158    }
159
160    println!("  发现威胁: {} 个", threats_found);
161    println!("  缓存命中: {} 个", cache_hits);
162
163    // 缓存管理演示
164    println!("\n💾 缓存管理:");
165    println!("=============");
166
167    println!("  当前缓存大小: {:?}", detector.cache_stats());
168
169    // 清理过期条目
170    detector.cleanup_cache();
171    println!("  清理后缓存大小: {:?}", detector.cache_stats());
172
173    // 清空缓存
174    detector.clear_cache();
175    println!("  清空后缓存大小: {:?}", detector.cache_stats());
176
177    println!("\n✨ 示例完成!");
178    Ok(())
179}

Trait Implementations§

Source§

impl Default for MailGuard

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,