Reputation: 2379
I've followed a few StackOverflow posts about how to convert MailMessage to a MIME String. So far, I just can't get it to work. I've gotten around all the errors and specifics with .NET 4.5 but for some reason my string is empty and my stream length is always 0. Any help would be appreciated.
Call to Function:
MailMessage message = new MailMessage("[email protected]", "[email protected]", "Test", "Test");
Console.WriteLine(ConvertMailMessageToMemoryStream(message));
Function Code:
private static string ConvertMailMessageToMemoryStream(MailMessage message)
{
BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
Assembly assembly = typeof(SmtpClient).Assembly;
Type mailWriterType = assembly.GetType("System.Net.Mail.MailWriter");
MemoryStream stream = new MemoryStream();
ConstructorInfo mailWriterConstructor = mailWriterType.GetConstructor(flags, null, new[] { typeof(Stream) }, null);
object mailWriter = mailWriterConstructor.Invoke(new object[] { stream });
MethodInfo sendMethod = typeof(MailMessage).GetMethod("Send", flags);
sendMethod.Invoke(message, flags, null, new[] { mailWriter, true, true }, null);
var sr = new StreamReader(stream);
var str = sr.ReadToEnd();
MethodInfo closeMethod = mailWriter.GetType().GetMethod("Close", flags);
closeMethod.Invoke(mailWriter, flags, null, new object[] { }, null);
return str;
}
Upvotes: 0
Views: 1433
Reputation: 1209
You have to seek the stream to the beginning before reading it.
stream.Seek(0, SeekOrigin.Begin)
The sendMethod
leaves the pointer at the end so you cant read anything from it.
Upvotes: 1