Test sending emails without a SMTP server in .NET.
Sep1Written by:
2009/09/01 08:47 AM
Testing is so important to application development. In fact more time in the development cycle is used up in testing and design than in actual coding. Any Tom, Dick or Jane can code. But truly gifted developers can test, find and eliminate bugs.
What application today does not have the ability to send out emails? Most do, because it is important to communicate with your clients and readers. So including the ability to send out emails is important.
But what if you do not have an SMTP server set up or available to you? How do you then test your email module to make sure that it is actually working, that the structure is correct, that it looks appealing, and so on?
Well the obvious is to either install an SMTP server, or relay through one you have permission to relay through. But this takes time and bandwidth, especially in countries like South Africa where bandwidth is expensive.
It wasn’t until recently that I found that you don’t need to have access to an SMTP server to test your code.
In fact, this little trick will allow you to send and read the email without clogging up your email client or bogging down your SMTP server with email you only wanted for testing purposes.
The secret is in the delivery method. Check out this small bit of code.
SmtpClient smtp = new SmtpClient();
MailAddress from = new MailAddress("me@u.com");
MailAddress to = new MailAddress("robert@test.com");
MailMessage message = new MailMessage();
message.Subject = "Test";
message.Body = "Body Message";
message.IsBodyHtml = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
smtp.PickupDirectoryLocation = @"d:\mail";
smtp.Send(message);
Notice the "DeliveryMethod" and the "PickupDirectoryLocation" . This will drop your email message in the d:\mail directory as an *.eml file which you can open with Outlook Express.
But now you can easily forget to take out or change the “DeliveryMethod”. So the best place to change that with ease is to put this into either the app.config or web.config files.
<mailSettings>
<smtp from="you@domain.com"
deliveryMethod="SpecifiedPickupDirectory">
<specifiedPickupDirectory
pickupDirectoryLocation="d:\tmp"/>
</smtp>
</mailSettings>
And now your code can look like this:
SmtpClient smtp = new SmtpClient();
MailMessage message = new MailMessage();
message.To.Add("robert@integralwebsolutions.co.za");
message.Subject = "Test";
message.Body = "Body Message";
message.IsBodyHtml = true;
smtp.Send(message);
Have fun testing. Let me know if this was of any help to you.
New here, or perhaps you've been here a few times? Like this post? Why not subscribe to this blog and get the most up to date posts as soon as they are published.
blog comments powered by