views:

4360

answers:

4

I want my asp.net mvc framework system to send an e-mail everytime a certain action (inside a certain controller) is fired off. Are there any third party libraries or .net standard ways to accomplish this?

+2  A: 

Create a BaseController from which all your other controllers inherits. In the BaseController override the OnActionExecuted Method and insert your code for sending the email.

public class BaseController : Controller
{
    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        // Send mail here
        base.OnActionExecuted(filterContext);
    }
}
TT
A: 

Well its not really hard to send a Email using .NET. You can just send the mail from inside your action.

But, I think we talk little about logging here, and for logging there is a range of 3th party libraries. I know there is one called Log4Net.

Most of these logging frameworks makes it possible to config how logs are stored, and porsibly also a setting to send a email, when it logs something.

But in your scenario, it would just write a plain simple mail function, that sends the mail, when the user enters the action. You can make look at: http://www.developer.com/net/asp/article.php/3096831 - its a demo of sending a mail using .NET - webforms though, but the basic things still apply to MVC.

Jesper Blad Jensen aka. Deldy
+7  A: 

A more up to date method would be to use System.Net.Mail - this is the 2.0 replacement for System.Web.Mail.

Something like this, called from either a BaseController (if there are other controllers that need this) the actual controller in question.

I have the following code inside a static class to handle mailing simple plain text items from the server:

internal static void SendEmail(MailAddress fromAddress, MailAddress toAddress, string subject, string body)
{
    var message = new MailMessage(fromAddress, toAddress)
                      {
                          Subject = subject,
                          Body = body
                      };

    var client = new SmtpClient("smtpServerName");
    client.Send(message);
}

Obviously, you'd probably want some error handling etc in there - Send can throw an exception for example if the server is refusing connections.

Zhaph - Ben Duguid
+1  A: 

The SmtpClient Class with the other System.Net.Mail classes are easily utilized from any .NET program to send mail. You just need to point it to an available and willing SMTP server.

gimel