Skip to content

Saving Emails to Disk in C#

Sending emails in C# is a simple task. All you need is a MailMessage object with your email and a SmtpClient to send it:

var toAddress = "[email protected]";
var fromAddress = "[email protected]";
var message = "your message goes here";

// create the email
var mailMessage = new MailMessage();
mailMessage.To.Add(toAddress);
mailMessage.Subject = "Sending emails is easy";
mailMessage.From = new MailAddress(fromAddress);
mailMessage.Body = message;

// send it (settings in web.config / app.config) 
var smtp = new SmtpClient();
smtp.Send(mailMessage);

The configuration for the SmtpClient is inside the web.config or app.config can look like this example from Sanjay kumar:

<configuration>
 <system.net>
        <mailSettings>
            <smtp from="[email protected]">
                <network host="smtp.gmail.com" 
                 port="587" 
                 userName="[email protected]" 
                 password="yourpassword" 
                 enableSsl="true"/>
            </smtp>
        </mailSettings>
</system.net>
</configuration>

Whenever your code is executed, your email will be sent using the specified mail server. While this is great for production, it’s a different story for testing your code. Do you really want to send all those emails?

A Different Delivery Method

The great benefit of using a configuration based approach with the mail configuration settings is that you can change the configuration in the app.config and don’t need to modify your code. If you switch the configuration from above with this one, then the SmtpClient will store the emails instead of sending them:

1
2
3
4
5
6
7
8
9
<configuration>
 <system.net>
  <mailSettings>
   <smtp deliveryMethod="SpecifiedPickupDirectory" >
    <specifiedPickupDirectory pickupDirectoryLocation="c:\temp\maildrop"/>
   </smtp>
  </mailSettings>
 </system.net>
</configuration>

Attention: make sure that the pickup directory exists. Otherwise you will get an exception.