Sending emails from web applications is a common task, but when working on or testing systems with real email addresses, it’s important to prevent recipients from receiving unintended emails, especially if real data is being used. In this blog post, I’ll show you how to configure ASP.NET SMTP client to write emails to disk instead of sending them out using the “Store e-mail in pickup directory” feature in IIS.
- SMTP Settings for Web Applications:
You can define SMTP settings in the web.config file under the system.web => mailsettings node. To create an SmtpClient using these settings, simply instantiate it with an empty constructor:
csharpvar smtpClient = new SmtpClient();
- What is a Pickup Directory?
Communicating with an SMTP server using the SMTP protocol can add unnecessary overhead to your network and SMTP server. Instead, clients can write their emails to a folder (called a pickup directory) that the SMTP server can access. This reduces resource usage, as the SMTP server only needs to forward the emails. File operations are much faster than communication over the SMTP protocol.
- Configuring ASP.NET SMTP to Use a Pickup Directory:
To configure your ASP.NET application to use a pickup directory, update your web.config file as follows:
xml<system.net>
<mailSettings>
<smtp deliveryMethod="SpecifiedPickupDirectory">
<specifiedPickupDirectory pickupDirectoryLocation="c:\temp\maildrop\"/>
</smtp>
</mailSettings>
</system.net>
Important points to remember:
- The pickup directory must physically exist, as it won’t be created automatically.
- IIS (or Cassini) must have write permissions to the pickup directory.
- Check your code for hardcoded SMTP settings and ensure there are no custom settings used for SMTP.
- Your emails will now be written to the pickup directory and not sent to recipients.
- Advanced Scenario: Configuring SmtpClient in Code:
In some cases, you might need to support multiple SMTP servers, or your configuration might not be stored in the web.config file. In these situations, you can initialize the SmtpClient in code as follows:
csharpvar smtpClient = new SmtpClient();
smtpClient.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
smtpClient.PickupDirectoryLocation = pickupFolder;
- Using IIS SMTP Service Pickup Directory:
If you have set up IIS with SMTP service, you can configure your ASP.NET application to use the IIS pickup folder by using the following setting for the delivery method:
csharpSmtpDeliveryMethod.PickupDirectoryFromIis
You can also set this in the web.config file:
xml<system.net>
<mailSettings>
<smtp deliveryMethod="PickupDirectoryFromIis" />
</mailSettings>
</system.net>
Conclusion:
By using the built-in email features of ASP.NET, you can easily prevent staging websites from sending emails and avoid using custom code to handle this task. Configuring your application to use a pickup directory is a simple and elegant solution that reduces the amount of code you need to support emails.