-
-
Save bczhc/888c093e658ea8d82df0be82c53a7b5d to your computer and use it in GitHub Desktop.
拉取126邮箱的垃圾邮件和广告邮件
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use imap::{Connection, Session}; | |
| use std::fs::{self, File}; | |
| use std::io::Write; | |
| use std::net::TcpStream; | |
| const JUNK_FOLDER_NAME: &str = "&V4NXPpCuTvY-"; | |
| const ADS_FOLDER_NAME: &str = "&Xn9USpCuTvY-"; | |
| const SAVE_DIR: &str = "pulled"; | |
| fn download_emails(session: &mut Session<Connection>, folder: &str) -> anyhow::Result<()> { | |
| // 1. 切换到目标文件夹 | |
| session.select(folder)?; | |
| // 2. 搜索所有邮件的 UID | |
| let query = "ALL"; | |
| let ids = session.uid_search(query)?; | |
| if ids.is_empty() { | |
| println!("文件夹 [{}] 为空。", folder); | |
| return Ok(()); | |
| } | |
| println!("开始从 [{}] 下载 {} 封邮件...", folder, ids.len()); | |
| for uid in ids { | |
| // 3. 获取邮件完整原始数据 (RFC822) | |
| let messages = session.uid_fetch(uid.to_string(), "RFC822")?; | |
| if let Some(msg) = messages.iter().next() { | |
| let body = msg.body(); | |
| if let Some(body) = body { | |
| // 4. 构造文件名并保存 | |
| // 简单处理文件夹名中的特殊字符,避免路径问题 | |
| let safe_folder_name = folder.replace("&", "").replace("-", ""); | |
| let file_path = format!("{}/{}_{}.eml", SAVE_DIR, safe_folder_name, uid); | |
| let mut file = File::create(&file_path)?; | |
| file.write_all(body)?; | |
| println!("已保存: {}", file_path); | |
| } | |
| } | |
| } | |
| Ok(()) | |
| } | |
| fn main() -> anyhow::Result<()> { | |
| let password = "xx"; | |
| let domain = "imap.126.com"; | |
| let email = "bczhc0@126.com"; | |
| // 确保本地目录存在 | |
| fs::create_dir_all(SAVE_DIR)?; | |
| let client = imap::ClientBuilder::new(domain, 993).connect()?; | |
| let mut session = client.login(email, password).map_err(|e| e.0)?; | |
| // 网易邮箱必需的 ID 验证 | |
| session.id(&[("name", Some("rust-downloader")), ("version", Some("1.0.0"))])?; | |
| // 执行下载任务 | |
| download_emails(&mut session, JUNK_FOLDER_NAME)?; | |
| download_emails(&mut session, ADS_FOLDER_NAME)?; | |
| println!("\n所有邮件已保存至 '{}' 文件夹。", SAVE_DIR); | |
| session.logout()?; | |
| Ok(()) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment