2.3 邮件附件的提取
邮件中的附件信息由对应的Content-Type域、Content-Transfer-Encoding域、Content-Disposition域和multipart/mixed类型定义,前三个域定义附件的类型、名称和编码方式,multipart/mixed则定义附件同邮件其它内容的分段标识。基本格式如下:
--boundary分段标识
Content-Type: application/msword;
name="readme.doc"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
filename=" readme.doc "
……
文件内容的Base64编码
……
--boundary分段标识
示例代码:提取邮件附件
//boundaryMixed代表已经提取出的multipart/mixed类型的boundary标识
//DecodeBase64为自定义的base64解码函数
//DecodeQuotedPrintable为自定义的quoted-printable解码函数
string emailContent = “……”;//emailContent中存储的是邮件内容
string pat = @"\r\nContent-Type:\s*(?<filetype>\S*);\s*name=""(?<name>\S*)""\s*Content-Transfer-Encoding:\s*(?<encoding>\S*)\s*Content-Disposition:\s*attachment;\s*filename=""(?<filename>\S+)""\s+(?<content>[\S|\r\n]+)" + "--" + boundaryMixed;
MatchCollection myMatches = Regex.Matches(emailContent,pat,RegexOptions.Singleline);
foreach(Match nextMatch in myMatches)
{
//提取附件的类型、编码方式、文件名、内容信息
GroupCollection myGroup = nextMatch.Groups;
string fileType = myGroup["filetype"].ToString();
string encoding = myGroup["encoding"].ToString();
string fileName = myGroup["filename"].ToString();
string content = myGroup["content"].ToString().Trim();
byte[] attachFile;
//根据附件的编码方式对提取出的附件内容进行解码
if(encoding == “base64”)
{
attachFile = DecodeBase64 (content);
}
if(encoding == “quoted-printable”)
{
attachFile = DecodeQuotedPrintable (content);
}
//将解码后的内容写入磁盘 FileStream fs = new FileStream("c:\\" + fileName,
FileMode.CreateNew);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(attachFile);
bw.Close();
fs.Close();
}
上面的程序从邮件原文中提取出附件信息,并根据附件采用的编码类型进行解码,然后将解码后的内容按照原文件名存储到C盘根目录。同样,如果附件的文件名是中文或者其它需要编码的文字,则首先需要对文件名进行解码。