I got a System.Net.Mail MailMessage object and want to save it to a documentset after sending. This object contains sender, to, cc, Html body and attachments.

How can I save it to a documentset?

I found some ways to use "save"-Methodes but they all just support local path like this on CodePlex.

At the end I just want an .eml or .msg in my folder.

Thanks to your answer i got this working fine:

MemoryStream stream = new MemoryStream();

Assembly assembly = typeof(SmtpClient).Assembly;
Type mailWriterType = assembly.GetType("System.Net.Mail.MailWriter");

ConstructorInfo mailWriterContructor = mailWriterType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(Stream) }, null);
object mailWriter = mailWriterContructor.Invoke(new object[] { stream });
MethodInfo sendMethod = typeof(MailMessage).GetMethod("Send", BindingFlags.Instance | BindingFlags.NonPublic);
sendMethod.Invoke(msg, BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { mailWriter, true }, null);

string emailTitle = string.Concat(documentSet.Folder.ServerRelativeUrl, name, ".eml");

stream.Seek(0, SeekOrigin.Begin);
byte[] data = new byte[stream.Length];
stream.Read(data, 0, (int)stream.Length);

SPFile file = documentSet.Folder.Files.Add(emailTitle, data, true);

1 Answer 1


Judging from the link you reported, the Save method calls a FileStream object. Being a stream, the FileStream can be replaced by a MemoryStream.

// Create MemoryStream object
MemoryStream stream = new MemoryStream();

// Get reflection info for MailWriter contructor
// [omitted for brevity]

// Construct MailWriter object with our MemoryStream
object _mailWriter = _mailWriterContructor.Invoke(new object[] { stream });

Then, it is just a matter of saving this stream to your document set, like this:

SPFolder ds = web.GetFolder("http://server/documentsetname");
byte[] data = new byte[stream.Length];
stream.Read(data, 0, (int)stream.Length); //make sure this is reliable, otherwise find other ways to convert to a byte array
ds.Files.Add("http://server/shared%20documents/documentsetname/your.msg", data);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.