Testing send mail logic using “<specifiedPickupDirectory>” element

Quite often it happens that we have logic of sending mails through .Net applications which we are unable to test correctly during development due to following reasons.

  1. We don’t want to actually send mails to the concerned person
  2. We dont have smtp server running on our development / testing machines

In such cases we usually have two options , either comment out the logic or install some third party fake smtp  server / emulator.

While going through MSDN I stumbled upon a very nice inbuilt feature which can be of great help in above scenarios.

Usually  our mail sending logic looks more  or less like below code

Class File:

MailMessage mail = new MailMessage();
            SmtpClient SmtpServer = new SmtpClient(); 

            mail.From = new MailAddress("<FromEmailAddress>@gmail.com");
            mail.To.Add("<ToEmailAddress>@yahoo.co.in");
            mail.Subject = "Demo Subject";
            mail.Body = "Testing send mail through Gmail"; 

            SmtpServer.Send(mail);

Config:

<system.net>
 <mailSettings>
      <smtp from="<FromEmailAddress>@gmail.com">
        <network host="smtp.gmail.com" port="587" userName="<UserName>" password="<Password>" enableSsl="true" />
      </smtp>
    </mailSettings>
    </system.net>

Now by using “specifiedPickupDirectory” element  in config you can choose a directory on the local machine where all the emails will be created (but will not be sent).Change the above config snippet as shown below and you are done.

<system.net>
     <mailSettings>
    <smtp deliveryMethod="SpecifiedPickupDirectory" from="<FromEmailAddress>@Gmail.com">
        <specifiedPickupDirectory pickupDirectoryLocation="c:\email"/>
    </smtp>
    </mailSettings>
  </system.net>

On executing the code with above configuration you will see the email message file generated in the pickup directory which can be opened by outlook or a free eml file reader (in some cases you should even be able to open it through Notepad).

image

Tagged on: , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.