前段時間做了個關于郵件的東西,記錄一下如何解析和保存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讀入數(shù)據(jù)流
// oMsg.DataSource.OpenObject(stm, "_stream"); //將EML數(shù)據(jù)流載入到CDO.Message
// }
// catch (IOException ex)
// {
// using (StreamWriter writer = new StreamWriter(GlobalConstants.MailLogPath, true))
// {
// writer.WriteLine("解析eml文件出現(xiàn)異常" + 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;