I use email as a notification mechanism a lot, and often in class I'll demo sending email via a technique that I use frequently when developing code. It allows you to simulate sending an email message.
The trick to doing this is not to hardcode things like host, port, etc. for your SMTP server when you use System.Net.Mail to send mail. Instead, use the default ctor for SmtpClient as I've done in the code below.
static void Main(string[] args)
{
// note the use of the MailAddress class
// this allows me to specify display names as well as email addresses
MailAddress from = new MailAddress("admin@fabrikam.com", "Fabrikam Website");
MailAddress to = new MailAddress("mari@fabrikam.com", "Mari Joyce");
MailMessage msg = new MailMessage(from, to);
msg.Subject = "Testing 123";
msg.Body = "This is only a test!";
// note use of default ctor
// this looks in config to figure out how to send mail
new SmtpClient().Send(msg);
}
What you're telling .NET by using the default ctor for SmtpClient is, "please use my config file to figure out how to send mail". Now you can use the system.net/mailSettings/smtp section in config to specify the details of your mail server, and all of the code in your app that is written to use the default SmtpClient ctor will inherit these settings. Here's an example of what the config on a production server might look like (if you put passwords in your config files, be sure to encrypt those sections):
<configuration>
<system.net>
<mailSettings>
<smtp deliveryMethod="Network">
<network host="mail.fabrikam.com"
port="25"
userName="WebsiteMailAccount"
password="whatever"/>
</smtp>
</mailSettings>
</system.net>
</configuration>
During development, I use different settings because I don't usually want to deal with the hassle of installing an SMTP server on my development box. Instead, I want email messages delivered as individual files in a directory on my hard drive (I always have a c:\mail directory on my development box for just this purpose):
<configuration>
<system.net>
<mailSettings>
<smtp deliveryMethod="SpecifiedPickupDirectory">
<specifiedPickupDirectory pickupDirectoryLocation="c:\mail"/>
</smtp>
</mailSettings>
</system.net>
</configuration>
Now when I run the program above, I get a .EML file in my c:\mail directory:
Outlook Express is normally registered as the viewer for .EML files, so double-click the file to view it:
If you've never seen this method of simulating email before, I hope you find it as useful as I have. Happy coding!
Posted
Aug 01 2008, 09:59 AM
by
keith-brown