I released a library a while back that makes some email functionality easier with a wrapper around the built in .NET email functionality called Email Notification. I prefer to use a library like this to segregate the email functionality from the code base of my application. The wrapper gives you the ability to easily configure emails using either fluent syntax or use the configuration file of your website or application. It also handles some of the common exceptions thrown by email servers and handles them for you. The project has been open sourced and can be found on Github here.
I’ll give you a quick an easy basic use case for the service in a web site instance. In a future post I’ll share with you an example of sending emails through a windows service quickly and painlessly.
So for this example I started with a basic MVC 4 project (you could use MVC 3). Once the project is setup, start with the configuration file. I’ll drop the following couple lines into the web.config. I set my SMTP server and port, tell it not to use SSL and tell it the server doesn’t require a login. I also want to make sure I tell it about my test email accounts used by my UI tester, this way I prevent mail from being sent out to these accounts when my auto UI test is activated.
<configSections>
<section name="EmailNotificationSettings" type="EmailNotification.Config.EmailNotificationConfigurationSectionHandler, EmailNotification" allowLocation="false" allowDefinition="Everywhere"/>
</configSections>
<EmailNotificationSettings isEnabled="true">
<ServerSettings smtpServer="smtp.myserver.com" smtpServerPort="25" isSSLEnabled="false" smtpServerConnectionLimit="-1" smtpServerPassword=""
smtpServerUser="" smtpServerRequiredLogin="false" useDefaultCredentials="true"/>
<TestEmailAccounts isTestEmailAccountsBlocked="true">
<add account="myserver.com"></add>
</TestEmailAccounts>
</EmailNotificationSettings>
Let’s create a view “Index.cshtml” that will send out a single email, this view uses a basic Email { To, From, Subject Body} model.
@{ Ajax.BeginForm("SendEmail", "Email", new AjaxOptions { HttpMethod = "POST", OnSuccess = "SendEmailSuccess"}); }
<div style="width:500px; background-color: #EEEEEE; border:solid 1px black; padding:5px;">
<div><span class="label">To:</span>@Html.TextBoxFor(t => t.To, new { style = "width:350px;" })</div>
<div><span class="label">From:</span>@Html.TextBoxFor(t => t.From, new { style = "width:350px;" })</div>
<div><span class="label">Subject:</span> @Html.TextBoxFor(t => t.Subject, new { style="width:350px;"})</div>
<div><span class="label">Body:</span>@Html.TextAreaFor(t => t.Body, new { style = "width:350px;" })</div>
<div style="text-align: center;">
<input type="submit" value="send" />
</div>
</div>
@{ Html.EndForm(); }
Now here comes the easy part, but also the meat, wiring up the controller to send the email. I grab the email from the view, convert the model to an email the Email Notification wrapper is able to read and send the email out using the configuration from the web.config. That result is then sent back to the view where its handled there through javascript.
[HttpPost]
public JsonResult SendEmail()
{
var email = new EmailMessage();
if (TryUpdateModel(email))
{
var emails = new List<MessageQueueEntity>
{
new MessageQueueEntity
{
To = email.To,
From = email.From,
Body = email.Body,
Subject = email.Subject,
BodyFormat = BodyFormat.PlainText,
Created = DateTime.Now
}
};
var configuration = Master.UseAppConfig().WithEmails(emails);
var result = Master.Execute(configuration);
return Json(result);
}
return new JsonResult { Data = new { IsSuccess = false} };
}
The javascript on the view is pretty simple, it will check to make sure that each of the emails sent to the wrapper were successful or not. If not successful I display the error message in an alert window.
<script type="text/javascript>
function SendEmailSuccess(data) {
console.log(data);
$.each(data.Emails, function (index, value) {
console.log(value);
if (value.SentException != null) {
alert("Email " + index + " couldn't be sent because: " + value.SentException.Message);
} else {
alert("Email " + index + " was successfully sent to : " + value.To);
}
});
}
</script>
Hopefully you find the Email Notification wrapper as useful as I do. I’ve included the example for you to download, the libraries source code can also be found on Github. As a bonus I threw in a multi-email example for some fun. If you find any issues with the library or have suggestions feel free to post an issue on the source at Github