Introduction

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.

Background

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.

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.

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.

Final note

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.

Share

About the Author

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.

A great article and the solution worked perfectly until last week.
Seems that Microsoft has changed the number of parameters for the internal send method. Do you have an update how to use this with .NET Framework 4.5 and higher?

Yes I've managed to make it work using community solutions, but not the article one.

The fix is as simple as fixing the number of parameters in an overload. The problem is that the article didn't mentioned it, by making another search. The article probably could be updated with almost no effort by the creator.

The article clearly states what might happen and actually did happen after it was written. For an article written 5 years ago intending to explain the process of using certain techniques and not to give a solution, I think you've missed the point of the article. However, I am glad you have managed to bring the code up to date and I have now added a note to the end of the article.

The article clearly states what might happen and actually did happen after it was written. For an article written 5 years ago intending to explain the process of using certain techniques and not to give a solution, I think you've missed the point of the article. However, I am glad you have managed to bring the code up to date and I have now added a note to the end of the article.

And that is exactly the spirit of the site and the goal of the message boards, to rise up possible bugs and let the author get ride of them. Technology evolve, why don't let the articles evolve with it?
My 5 to you

M.D.V.

If something has a solution... Why do we have to worry about?. If it has no solution... For what reason do we have to worry about?
Help me to understand what I'm saying, and I'll explain it better to you
Rating helpful answers is nice, but saying thanks can be even nicer.

Your vote and your arguments were (in my opinion) totally valid. But now, the author has edited the article with a fix. I think you should now be fair, have a look to the update and reconsider your vote.

M.D.V.

If something has a solution... Why do we have to worry about?. If it has no solution... For what reason do we have to worry about?
Help me to understand what I'm saying, and I'll explain it better to you
Rating helpful answers is nice, but saying thanks can be even nicer.

Well I changed my vote to a 5 stars (btw I was the one that voted 1 star before).

I believe that as I had to use this in my project with a very limited time to develop I was pretty mad at it when it didn't work, but as I've already said before in the end of the day it worked with some effort.

As the author updated the article and seens to be quite colaborative I think its more than fair that I change it to 5 stars.

Anyway thanks, and now the next fellas who might need it now have an easier way to fix it stated int the article itself.

Greate and very useful article. Thanks.
One note though. According to modern Microsoft "security trend" the Outlook opens saved .eml in the "sent" mode, and not in the edit window, because of lack "X-Unsent" header.
So I've added to the MailMessageExt class the new method SaveUnsent, that actually is the copy of Send method with minor changes. I know that it is not commomn enough, but it is what I need for my application.