Recently, you need to use. Net (C #) to save the mail Information as a local EML file. It seems like a hard job: First, you have to understand the mime protocol (RFC 2045 ~ 2049), and then write the code. Fortunately, some friends used to have such requirements and ready-made solutions. Haha: mailwriter has been implemented in the system. net. Mail namespace, but I don't know why it is not made public.
Use xenocode Fox 2007 (Community edition) to load system. dll and find the system. net. Mail. smtpclient class. You can see that the send (mailmessage) method contains the following two codes:
MailwriterWriter;
Writer = getfilemailwriter (pickupdirectorylocation );
Let's take a look at the getfilemailwriter method:
Internal mailwriter getfilemailwriter (stringPickupdirectory)
{
StringPath;
...
Do
{
GuidGuid1= Guid. newguid ();
StringPath2= Guid1.tostring () +". Eml";
Path = path. Combine (pickupdirectory, path2 );
}
While (file. exists (PATH ));
Return new mailwriter (New filestream (path, filemode. createnew ));
}
Looking deeper, we can see that mailwriter directly writes the mailmessage content into the ". eml" file and writes it according to the mime protocol, yeah!
The next step is to use the internal (internal) Class mailwriter. Of course, this is very simple:
Public static byte [] mailmessagetoarray (mailmessage MSG)
{
Const bindingflags flags = bindingflags. instance | bindingflags. nonpublic | bindingflags. flattenhierarchy;
Using (var ms = new memorystream ())
{
VaR Assembly = typeof (system. net. Mail. smtpclient). assembly;
VaR writertype = assembly. GetType ("system. net. Mail. mailwriter ");
VaR writer = activator. createinstance (writertype, flags, null, new object [] {MS },
Cultureinfo. invariantculture );
MSG. GetType (). getmethod ("send", flags). Invoke (MSG, new [] {writer, true });
Return Ms. toarray ();
}
}
If we use Versions later than C #3.0, we can also add extension methods for mailmessage, which is more natural to use. The Code is as follows:
// Define the Extension Method
Public static class mailmessageextend
{
Public static byte [] toarray (this mailmessage MSG)
{
Const bindingflags flags = bindingflags. instance | bindingflags. nonpublic | bindingflags. flattenhierarchy;
Using (var ms = new memorystream ())
{
VaR Assembly = typeof (system. net. Mail. smtpclient). assembly;
VaR writertype = assembly. GetType ("system. net. Mail. mailwriter ");
VaR writer = activator. createinstance (writertype, flags, null, new object [] {MS },
Cultureinfo. invariantculture );
MSG. GetType (). getmethod ("send", flags). Invoke (MSG, new [] {writer, true });
Return Ms. toarray ();
}
}
}
// Call
Private void button#click (Object sender, eventargs E)
{
VaR MSG = new mailmessage ();
...
VaR content = msg. toarray ();
...
}