For a project I was working on, I needed to create an EML file from the standard MailMessage class which exists in the System.Net.Mail namespace. I came across an article which describes how to extend the save functionality on the MailMessage class. Using the same technique I created an extension method which is able to save the MailMessage class as EML.
With this extension method in your solution you can create an EML file like this:
var mailMessage = new MailMessage(); | |
string eml = mailMessage.ToEml(); |
The extension method is implemented like this:
using System.IO; | |
using System.Net.Mail; | |
using System.Reflection; | |
using System.Text; | |
namespace Infrastructure.MailMessageExtensions | |
{ | |
public static class MailMessageExtensions | |
{ | |
public static string ToEml(this MailMessage message) | |
{ | |
var assembly = typeof(SmtpClient).Assembly; | |
var mailWriterType = assembly.GetType("System.Net.Mail.MailWriter"); | |
using (var memoryStream = new MemoryStream()) | |
{ | |
// Get reflection info for MailWriter contructor | |
var mailWriterContructor = mailWriterType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(Stream) }, null); | |
// Construct MailWriter object with our FileStream | |
var mailWriter = mailWriterContructor.Invoke(new object[] { memoryStream }); | |
// Get reflection info for Send() method on MailMessage | |
var sendMethod = typeof(MailMessage).GetMethod("Send", BindingFlags.Instance | BindingFlags.NonPublic); | |
// Call method passing in MailWriter | |
sendMethod.Invoke(message, BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { mailWriter, true, true }, null); | |
// Finally get reflection info for Close() method on our MailWriter | |
var closeMethod = mailWriter.GetType().GetMethod("Close", BindingFlags.Instance | BindingFlags.NonPublic); | |
// Call close method | |
closeMethod.Invoke(mailWriter, BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { }, null); | |
return Encoding.ASCII.GetString(memoryStream.ToArray()); | |
} | |
} | |
} | |
} |
Conclusion
EML files are perfect for storing the email message on your file system or in the database. The EML file contains all the data from the email, including attachments. You can open the EML in most mail clients and view the email.
Top comments (1)
Thank you for this useful post.