# ASP.NET MVC 3 Beta: Using WebMail helper to send e-mail

This far I have blogged about WebImage and Chart helpers. Now let’s see another new helper – WebMail – that you can easily use to send e-mails. WebMail is easy to configure and extremely easy to use. In this posting I will show you simple feedback form that uses WebMail to send feedback messages.

### Feedback view

As a first thing let’s create view for feedback form. I am using Razor view engine in this posting. Feedback view is really simple. It contains fields that user must fill and validation message that is shown when something is wrong.

@model dynamic @{    View.Title = "Feedback";    Layout = "~/Views/Shared/_Layout.cshtml";} <h2>Feedback</h2> <p>@Html.ValidationMessage("_FORM")</p> @using(Html.BeginForm()) {    <table>    <tr>        <td>Your e-mail:</td>        <td>@Html.TextBox("email")</td>    </tr>    <tr>        <td>Subject:</td>        <td>@Html.TextBox("subject")</td>    </tr>    <tr>        <td>Body:</td>        <td>@Html.TextArea("body")</td>    </tr>    </table>    <input type="submit" value="Send" />}

To be honest I have used no validation in this example. Validation message for _FORM is used to show exceptions when something went wrong. It makes it easier for you to play with this example.

### Sending e-mail using WebMail

Before we start sending e-mail I show you two controller actions. There actions are used to show feedback form and page that is shown when e-mail is successfully sent.

[HttpGet]public ActionResult Feedback(){    return View();}public ActionResult FeedbackSent(){    return View();}

I have shown no FeedbackSent view here. I am very sure you are able to create this simple view by yourselves. 🙂

Now let’s take a look at controller action that uses WebMail to send e-mail. Notice how I can easily use SmtpServer static property to set the address of SMTP server. There are more static properties that let you configure WebMail helper. In the case of exception the exception is shown on feedback form with stack trace. If e-mail is sent without errors then user is redirected to FeedbackSent view where he or she can read some bla-bla-bla about when answer is expectedly sent and so on.

[HttpPost]public ActionResult Feedback(string email, string subject, string body){    try    {        WebMail.SmtpServer = "my.smtp.server";        WebMail.Send(                "feedback[at]mycompany.domain",                subject,                body,                email            );         return RedirectToAction("FeedbackSent");    }    catch (Exception ex)    {        ViewData.ModelState.AddModelError("_FORM", ex.ToString());    }     return View();}

And now let’s take a look what’s going on in my mailbox where I sent my test messages.

Mission completed – seems like I can go to sleep now. 🙂

By the way, if you don’t specify sender when calling WebMail.Send() method then e-mail is sent out from DoNotReply@localhost address.