. Net has greatly improved the mail. smtpclient function since 2.0. It is easy to send emails. However, the US lacks the ability to save the email content as an EML file.
In fact, smtpclient and mailmessage have implemented this function, but this function is nonpublic and invisible outside the space.
Use reflector to decompile system. net. Mail. smtpclient. You can see:
In the send (mailmessage) method,Mailwriter filemailwriter = This. getfilemailwriter (this. pickupdirectorylocation );
Let's continue positioning.GetfilemailwriterThis method
The above code is highlighted. EmlAfter reading the logic, we can see that before smtpclient. Send, Mr also became a temporary EML file and then sent it out.
The key is in new mailwriter (New filestream (str2, filemode. createnew.
Next we will find our coreMailwriter:
As we can see from the above, mailwriter is an internal class, so we can't see it in the namespace that calls mail. smtpclient and so on. We need to use it now.Reflection(Reflection.
The complete implementation code is provided below:
/// <Summary> /// save mailmessage as an EML file // </Summary> /// <Param name = "MSG"> the mailmessage with content to be saved </param> /// <Param name = "emlfileabsolutepath"> path of the saved EML file </param> static void savetoeml (mailmessage MSG, string emlfileabsolutepath) {const bindingflags flags = bindingflags. instance | bindingflags. nonpublic | bindingflags. flattenhierarchy; using (memorystream MS = new memorystream () {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 );}}
Usage:
MailMessage msg = new MailMessage();msg.Subject = "hello, i am deltacat";msg.From = new MailAddress("deltacat@microsoft.com");msg.To.Add("zu14.cn@live.cn");msg.Body = "welcome to www.zu14.cn";SaveToEml(msg, @"d:\test.eml");
Good luck!