前段时间做了个关于邮件的东西,记录一下如何解析和保存eml文件的。
/// <summary>
/// 解析eml
/// </summary>
private void AnalyzeEmlFile()
{
// CDO.Message oMsg = new CDO.Message();
// ADODB.Stream stm = null;
// //读取EML文件到CDO.MESSAGE
// try
// {
// stm = new ADODB.Stream();
// stm.Open(System.Reflection.Missing.Value,
// ADODB.ConnectModeEnum.adModeUnknown,
// ADODB.StreamOpenOptionsEnum.adOpenStreamUnspecified,
// "", "");
// stm.Type = ADODB.StreamTypeEnum.adTypeBinary;//二进制方式读入
// stm.LoadFromFile(emlpath); //将EML读入数据流
// oMsg.DataSource.OpenObject(stm, "_stream"); //将EML数据流载入到CDO.Message
// }
// catch (IOException ex)
// {
// using (StreamWriter writer = new StreamWriter(GlobalConstants.MailLogPath, true))
// {
// writer.WriteLine("解析eml文件出现异常" + DateTime.Now + "/n" + ex.Message);
// writer.Close();
// }
// }
// finally
// {
// stm.Close();
// }
}
/// <summary>
/// 将mailmessage保存为.eml文件
/// </summary>
/// <param name="msg">待保存的具有内容的MailMessage</param>
/// <param name="emlFileAbsolutePath">保存后的eml文件的路径</param>
static void SaveToEml(MailMessage msg, string emlFileAbsolutePath)
{
//const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy;
//using (MemoryStream ms = new MemoryStream())
//{
// Assembly assembly = typeof(System.Net.Mail.SmtpClient).Assembly;
// Type tMailWriter = assembly.GetType("System.Net.Mail.MailWriter");
// object mailWriter = Activator.CreateInstance(tMailWriter, flags, null, new object[] { ms }, CultureInfo.InvariantCulture);
// msg.GetType().GetMethod("Send", flags).Invoke(msg, new object[] { mailWriter, true });
// File.WriteAllText(emlFileAbsolutePath, System.Text.Encoding.Default.GetString(ms.ToArray()), System.Text.Encoding.Default);
//}
}
第二种方法保存.eml(缺陷是保存的文件名为随机的guid )
//smtpClient.EnableSsl = false;
// smtpClient.PickupDirectoryLocation = mailPath;//要保存的路径
//smtpClient.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;