Wednesday, January 27, 2010

Configuring SmtpClient to drop emails in a folder on disk

Did you know that you can configure the built-in System.Net.Mail.SmtpClient to drop emails into a location on disk? This means that you don’t need an SMTP server for testing the email sending capabilities of your application.

You can find this advice in numerous places on the interweb, but I need to make a note here because every time I want to do it, I can’t remember the details and have to waste time browsing for it.

Simply put this configuration section in your App.config or Web.config file:

<system.net>
  <mailSettings>
    <smtp deliveryMethod="SpecifiedPickupDirectory">
      <specifiedPickupDirectory pickupDirectoryLocation="c:\temp\maildrop\"/>
    </smtp>
  </mailSettings>
</system.net>

Now when you have some code like this:

var smtpClient = new SmtpClient();
var message = new MailMessage("no-reply@suteki.co.uk", "mike@suteki.co.uk")
{
    Subject = "The subject",
    Body = "The body of the message"
};
smtpClient.Send(message);

You get a file deposited in C:\temp\maildrop called something like ec40a365-270f-49ac-9aa5-1e68ec6a4df1.eml that looks like this:

X-Sender: no-reply@suteki.co.uk
X-Receiver: mike@suteki.co.uk
MIME-Version: 1.0
From: no-reply@suteki.co.uk
To: mike@suteki.co.uk
Date: 27 Jan 2010 21:32:05 +0000
Subject: The subject
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: quoted-printable

The body of the message

Sweet!

5 comments:

  1. Thats really neat!
    btw .. you can also use this tool to do the same:
    http://www.toolheap.com/test-mail-server-tool/

    ReplyDelete
  2. Anonymous8:31 am

    If you want, you can also do it in code rather than mucking around in the config files:
    smtp = new SmtpClient();
    smtp.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
    smtp.PickupDirectoryLocation = "C:\temp";

    ReplyDelete
  3. Sure did. One of the many tips I picked up from Stackoverflow.com. I think it's one of those handy but little known features!

    ReplyDelete
  4. Now how can i send the mail to the end user from this pickup folder?
    Do i need to write some extra scripts or will it be executed automatically?
    In case of extra script needed can some one point out any samples?

    ReplyDelete
  5. Anonymous7:22 pm

    Can some answer jibin's question please...i want to ask the same question.

    ReplyDelete

Note: only a member of this blog may post a comment.