Click here to Skip to main content
13,409,878 members (37,691 online)
Click here to Skip to main content
Add your own
alternative version


73 bookmarked
Posted 11 Jan 2009

Adding Save() functionality to System.Net.Mail.MailMessage

, 19 Nov 2014
Rate this:
Please Sign up or sign in to vote.
Using a combination of Reflector, Reflection, and C# 3.0 extension methods to add Save(string FileName) functionality to MailMessage in System.Net.Mail.


This article is going to use some simple techniques to analyse an existing .NET framework class and to extend it in a way the original developers did not intend.


I’ve been recently working on a project related to batch generating large numbers of emails for sending at a later stage. The MailMessage class appeared to provide the functionality I needed. It allowed me to add both plain text and HTML content, and using the DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory of SmtpClient, I could generate the emails to a file folder. However, when using this approach, I ran into a problem ...

One of the requirements of my project specified that I needed to control the filename used to output the email so that multiple jobs could be run concurrently and the filename could in some way relate the email to the job that run it. I also wanted to append a sequence number so that I could use this as a way for jobs to continue from where they left off if they failed.

The SmtpClient class has a Send(MailMessage Message) method which, when the PickupDirectoryLocation is specified and DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory, generates the email in that directory. However, the file name used by SmtpClient appeared to be a random Guid. No where does the standard SmtpClient or MailMessage expose a way for me to choose the filename used for output or even feedback the filename that was used.

Using Reflector to analyse existing classes

Not choosing to give up on using MailMessage and therefore opt for a third party component outside of the .NET framework, I embarked on finding a way of extending MailMessage and SmtpClient to provide the functionality I needed.

First, I used the excellent Reflector tool to analyse the MailMessage and SmtpClient classes to find out what they were really doing ‘under the hood’. You can download this free from RedGate.

Pointing Reflector at the SmtpClient.Send() method told me two things. When a pickup directory is specified, SmtpClient.Send() creates a MailWriter object called fileMailWriter using the GetFileMailWriter(string Path) method.

To actually generate the email, it then calls a Send() method on the MailMessage object, passing the newly created MailWriter object.


To investigate further, I looked at what was happening in the SmtpClient.GetFileMailWriter() method.


As expected, the disassembled code shows that this method creates a random filename with Guid.NewGuid() + “.eml”. It then creates a MailWriter object, passing it a standard FileStream.

From Reflector to Reflection

So, at this stage, I knew what was happening when I called SmtpClient.Send(message). But, how could I change this behaviour so that I could generate an email with my own specified filename?

I basically wanted to create a MailWriter object with my own FileStream and then pass it to MailMessage.Send(). However, Microsoft has not exposed this functionality to me. The MailWriter class, GetFileMailWriter(), and MailMessage.Send() methods are all marked as internal, so I couldn’t construct or invoke these methods in the standard way.

This is where Reflection stepped in. I could use Reflection to construct an internal MailWriter and then again to invoke the internal Send() method on MailMessage.

Assembly _assembly = typeof(SmtpClient).Assembly;
Type _mailWriterType = _assembly.GetType("System.Net.Mail.MailWriter");
// Create FileStream object
FileStream _myFileStream = new FileStream(_myFileName, FileMode.Create);

// Get reflection info for MailWriter contructor
ConstructorInfo _mailWriterContructor =
      	    BindingFlags.Instance | BindingFlags.NonPublic,
            new Type[] { typeof(Stream) }, 

// Construct MailWriter object with our FileStream
object _mailWriter = 
    _mailWriterContructor.Invoke(new object[] { _myFileStream });
// Get reflection info for Send() method on MailMessage
MethodInfo _sendMethod =
        BindingFlags.Instance | BindingFlags.NonPublic);

// Call method passing in MailWriter
    BindingFlags.Instance | BindingFlags.NonPublic,
    new object[] { _mailWriter, true },
  • First, I needed to get the type of the MailWriter object to be able to construct it. We can use the exposed SmtpClient class to do this indirectly. First, I obtained the assembly that SmtpClient is contained in, and then used GetType() to get a reference to the MailWriter type.
  • Then, I needed to invoke the internal constructor of the MailWriter type to create a MailWriter object. I created my own FileStream object and passed this in.
  • Next, again using Reflection, I invoked the Send() method of a MailMessage object passing in my MailWriter object.

And that was it – the generated email was created to the filename specified when constructing my FileStream class. By using Reflection, I had reused internal classes and methods in the System.Net.Mail namespace to save a mail to the file system with my own filename – exactly what I needed.

Finishing touches - extension method

For a final nice touch, I could now wrap this up by using a new feature of C# 3.0 called extension methods. By using an extension method, you can add a Save(string FileName) method to the MailMessage class as if it was put there in the first place.

Shown below is the complete extension method:

public static class MailMessageExt
    public static void Save(this MailMessage Message, string FileName)
        Assembly assembly = typeof(SmtpClient).Assembly;
        Type _mailWriterType = 

        using (FileStream _fileStream = 
               new FileStream(FileName, FileMode.Create))
            // Get reflection info for MailWriter contructor
            ConstructorInfo _mailWriterContructor =
                    BindingFlags.Instance | BindingFlags.NonPublic,
                    new Type[] { typeof(Stream) }, 

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

            // Get reflection info for Send() method on MailMessage
            MethodInfo _sendMethod =
                    BindingFlags.Instance | BindingFlags.NonPublic);

            // Call method passing in MailWriter
                BindingFlags.Instance | BindingFlags.NonPublic,
                new object[] { _mailWriter, true },

            // Finally get reflection info for Close() method on our MailWriter
            MethodInfo _closeMethod =
                    BindingFlags.Instance | BindingFlags.NonPublic);

            // Call close method
                BindingFlags.Instance | BindingFlags.NonPublic,
                new object[] { },

Basically, we have created a static method in a static class. The thing that marks this method out to be an extension method is the first parameter, this MailMessage Message. The first parameter when marked with this <ObjectType> says that this method is to extend the <ObjectType> class, in this case the MailMessage class.

Now, we can call our extra functionality like so:

MailMessage _testMail = new MailMessage();
_testMail.Body = "This is a test email";
_testMail.To.Add(new MailAddress(""));
_testMail.From = new MailAddress("");
_testMail.Subject = "Test email";

Final note

What we have achieved here is:

  • The ability to determine how something works internally using Reflector, including identifying internal classes and methods.
  • Use Reflection to make use of classes and methods which were not originally exposed to outside developers.
  • Wrap up extra functionality using extension methods.

Of course, as with most things, there is a downside to the approach I have taken.

One of the major things is that because we are using Reflection to get around the original restrictions put in place by Microsoft in this case, they are free to change their ‘internal’ implementation of System.Net.Mail in future framework releases, which could break our implementation. For example, what is to stop them changing the name of the MailWriter class to something else as it wasn’t exposed to us in the first place.

NOTE: Since this article was written, Microsoft have changed the parameters of the MailMessage.Send() method in .NET 4.5 which causes the existing code to fail. Various members have provided solutions to this in the comments on the article.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Allan Eagle
Software Developer Globe Business Publishing Ltd
United Kingdom United Kingdom
Started tinkering on an old BBC Microcomputer using BBC BASIC and progressed up to dabbling with C and ARMCode on an Acorn RiscPC. Moving to the PC platform I progressed from C++ to now a lot of C# and ASP.NET.

You may also be interested in...

Comments and Discussions

GeneralRe: Update with fix for .NET 4.5 Pin
Member 150124928-Feb-14 22:16
memberMember 150124928-Feb-14 22:16 
GeneralRe: Update with fix for .NET 4.5 Pin
Berend Engelbrecht5-Aug-14 21:06
memberBerend Engelbrecht5-Aug-14 21:06 
GeneralRe: Update with fix for .NET 4.5 Pin
windforce@hotmail.com11-Nov-14 9:17
memberwindforce@hotmail.com11-Nov-14 9:17 
QuestionCan any one let me know "How to get the above piece of code to work with .Net Framework 2.0"? Pin
GreatVision9-Jul-12 21:55
memberGreatVision9-Jul-12 21:55 
QuestionSuperb man... Pin
suri197115-Dec-11 1:36
membersuri197115-Dec-11 1:36 
GeneralWhy not just read the source code that Microsoft provides? Pin
Andy Missico1-Nov-11 21:07
memberAndy Missico1-Nov-11 21:07 
QuestionHow to load EML file Pin
Member 80825016-Sep-11 20:34
memberMember 80825016-Sep-11 20:34 
GeneralVB.Net Version Pin
Jeff Law6-Mar-11 15:58
memberJeff Law6-Mar-11 15:58 
I re-wrote this in VB.Net and added a few extra functions, like checking for existing files of the same name.

Works a treat!

Many thanks
Jeff Law
New Zealand

GeneralRe: VB.Net Version Pin
Lars Buhl Schamaitat21-Mar-11 21:32
memberLars Buhl Schamaitat21-Mar-11 21:32 
GeneralRe: VB.Net Version Pin
Jeff Law21-Mar-11 23:30
memberJeff Law21-Mar-11 23:30 
GeneralRe: VB.Net Version [modified] Pin
Lars Buhl Schamaitat28-Mar-11 2:31
memberLars Buhl Schamaitat28-Mar-11 2:31 
GeneralRe: VB.Net Version Pin
dominick Scalzo21-Jun-11 11:42
memberdominick Scalzo21-Jun-11 11:42 
GeneralRe: VB.Net Version Pin
Jeff Law21-Jun-11 11:57
memberJeff Law21-Jun-11 11:57 
QuestionSupporting BCC Pin
skiltzy24-Nov-10 18:06
memberskiltzy24-Nov-10 18:06 
AnswerRe: Supporting BCC Pin
Allan Eagle24-Nov-10 22:51
memberAllan Eagle24-Nov-10 22:51 
GeneralRe: Supporting BCC Pin
skiltzy24-Nov-10 22:55
memberskiltzy24-Nov-10 22:55 
QuestionDoes this support attachments? Pin
broettge21-Jul-10 14:14
memberbroettge21-Jul-10 14:14 
AnswerRe: Does this support attachments? Pin
Allan Eagle21-Jul-10 15:33
memberAllan Eagle21-Jul-10 15:33 
GeneralRe: Does this support attachments? [modified] Pin
broettge22-Jul-10 9:31
memberbroettge22-Jul-10 9:31 
QuestionIs that thread-safe? Pin
microsoftcsharp6-Mar-10 0:29
membermicrosoftcsharp6-Mar-10 0:29 
AnswerRe: Is that thread-safe? Pin
Allan Eagle21-Jul-10 15:45
memberAllan Eagle21-Jul-10 15:45 
AnswerRe: Is that thread-safe? Pin
mswlim11-Jan-12 18:08
membermswlim11-Jan-12 18:08 
QuestionCan we get stream before sending the mail? Pin
yogesh.rain14-Jan-10 0:26
memberyogesh.rain14-Jan-10 0:26 
AnswerRe: Can we get stream before sending the mail? Pin
Allan Eagle21-Jul-10 15:39
memberAllan Eagle21-Jul-10 15:39 
GeneralI never thought so Pin
Sameers (theAngrycodeR )17-Nov-09 22:14
memberSameers (theAngrycodeR )17-Nov-09 22:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.180221.1 | Last Updated 19 Nov 2014
Article Copyright 2009 by Allan Eagle
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid