使用mailparse的ParsedMail :: get_body时,二进制附件已损坏

时间:2018-02-12 09:56:02

标签: rust mime

我正在尝试使用Rust解析保存为MIME文件的电子邮件。我能够提取身体和附件。当附件是CSV文件时,一切正常。当文件是PDF或XLSX文件时,保存的文件已损坏。我怀疑编码有问题,因为当我检查标题时我得到了

Content-Type = "application/vnd.openxmlformats officedocument.spreadsheetml.sheet"

这是我的代码,适用于CSV但不适用于XLSX:

extern crate base64;
extern crate mailparse;

use mailparse::*;
use std::fs::File;
use std::string::*;
use std::io::prelude::*;

fn main() {
    let mut file = File::open("test_mail").unwrap();
    let mut contents = String::new();
    let _silent = file.read_to_string(&mut contents);
    let parsed = parse_mail(contents.as_bytes()).unwrap();

    // This is the attached file
    let attached_file = parsed.subparts[2].get_body().unwrap();

    // Write the file
    let mut out_file = File::create("out_file.xlsx").unwrap();
    out_file.write_all(attached_file.as_bytes()).unwrap();

    println!("Done")
}

我正在使用Rust 1.23.0,Cargo 0.24.0,我在Debian上运行它。

1 个答案:

答案 0 :(得分:1)

ParsedMail::get_body仅适用于文本数据(可以转换为unicode字符串)。您想使用ParsedMail::get_body_raw访问二进制附件:

let attached_file = parsed.subparts[2].get_body()_raw.unwrap();

// Write the file
let mut out_file = File::create("out_file.xlsx").unwrap();
out_file.write_all(attached_file).unwrap();
相关问题