Thursday 25 October 2012

Problems with sending email over SMTP in .NET?

I occasionally have problems sending email to my own local SMTP server, and get pretty paranoid that your recipient might actually get a test email that they're not actually supposed to get.

You know you haven't set SMTP up properly on a .NET website when you get an error like this: "Failure sending mail" or "No connection could be made because the target machine actively refused it 127.0.0.1:25"

My advice? Don't bother setting SMTP up on your local box. What's the point when you can intercept all outgoing email and view what you're going to send (and to whom) with a little application that sits in your system tray!

Enter SMTP4Dev. I'm going to sound like a JML advert, or possibly sound like I work for them (I don't), but I can't recommend this little application enough. It requires no config whatsoever provided that you're going to use port 25 for SMTP, and it's free!

That URL again: SMTP4Dev.

Friday 19 October 2012

Elmah won't work in .NET MVC 3 won't work with CustomErrors

I've been doing a lot of work on an MVC 3 application recently, and it's already got Elmah installed ready to report all sorts of errors to help you debug your application.

Except it doesn't.

When the <customerrors /> element of the web.config is set to "On", a friendly error message appears when a user experiences an issue, but Elmah doesn't capture the error. This is because ASP.NET swallows the exception, and this method in the global.asax.cs is responsible:

This line ensures that the "handle error" attribute is attached to all controllers, and the exception's lost.

I found a really nice neat solution on a StackOverflow question, but it's a long way down the page, so I'm recording it here for easier reference.

Create a class that looks like this:

And reference it in the global.asax.cs file ahead of the other attribute like this:

The various answers and a full discussion of the problem are available at this StackOverflow question, but it's quite a long way down the page. It's really worth a read though.