ASP.NET MVC5 - SendEmail and save it with EF6
Using MVC, Entity Framework, and ASP.NET Scaffolding, you can create a web application that provides an interface to an existing database table. This demo shows you how to automatically generate code that enables users to display, edit, create, and delete data that resides on the database. The generated code corresponds to the columns in the database table.
This demo focuses on using ASP.NET Scaffolding to generate the controllers and views.
STEP1 - Create new project on Visual Studio 2015
Open Visual Studio
Create new ASP.NET Web Application Project
Give a name to the project (in this case I call him MVC5)
Select Template MVC
https://code.msdn.microsoft.com/site/view/file/144481/1/1.PNG
STEP2 - Create class Email
Add new class to the project (this class represents a table, and the properties the colums of that table)
Give a name to that class (in my sample I call him EmailModel)
On the class create the following code:
C#
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Dynamic;
using System.Linq;
using System.Web;
namespace MVC5.Models
{
public class Email
{
public int ID { get; set; }
public string To { get; set; }
public string Subject { get; set; }
public string Message { get; set; }
}
public class EmailDBContext : DbContext
{
public DbSet<Email> Emails { get; set; }
}
}
Put the class inside the Models folders, just to organize your code.
STEP3 - Create controller with views using Entity Framework
Add new Scaffolded to the project (new item existent on MVC5)
https://code.msdn.microsoft.com/site/view/file/106308/1/MVC53.jpg
Choose option MVC5 Controller with views using Entity Framework
https://code.msdn.microsoft.com/site/view/file/144482/1/2.PNG
Click Add
If you receive an error, it may be because you did not build the project in the previous section. If so, try building the project, and then add the scaffolded item again.
After the code generation process is complete, you will see a new controller and views in your project.
STEP4 - Controller and Views Generation
The Controller was automatically created with CRUD operations
C#
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Web.Mvc;
using MVC5.Models;
namespace MVC5.Controllers
{
public class EmailsController : Controller
{
private EmailDBContext db = new EmailDBContext();
// GET: Emails
public async Task<ActionResult> Index()
{
return View(await db.Emails.ToListAsync());
}
// GET: Emails/Details/5
public async Task<ActionResult> Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Email email = await db.Emails.FindAsync(id);
if (email == null)
{
return HttpNotFound();
}
return View(email);
}
// GET: Emails/Create
public ActionResult Create()
{
return View();
}
// POST: Emails/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "ID,To,Subject,Message")] Email email)
{
if (ModelState.IsValid)
{
db.Emails.Add(email);
await db.SaveChangesAsync();
Services.EmailService emailService = new Services.EmailService();
await emailService.SendEmailAsync(email.To, email.Message, email.Subject);
return RedirectToAction("Index");
}
return View(email);
}
// GET: Emails/Edit/5
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Email email = await db.Emails.FindAsync(id);
if (email == null)
{
return HttpNotFound();
}
return View(email);
}
// POST: Emails/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "ID,To,Subject,Message")] Email email)
{
if (ModelState.IsValid)
{
db.Entry(email).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(email);
}
// GET: Emails/Delete/5
public async Task<ActionResult> Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Email email = await db.Emails.FindAsync(id);
if (email == null)
{
return HttpNotFound();
}
return View(email);
}
// POST: Emails/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id)
{
Email email = await db.Emails.FindAsync(id);
db.Emails.Remove(email);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
STEP5 - Create Email Service
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
namespace Services
{
public class EmailService
{
public async Task<bool> SendEmailAsync(string emailTo, string mailbody, string subject)
{
var from = new MailAddress("abc@abc.com");
var to = new MailAddress(emailTo);
var useDefaultCredentials = true;
var enableSsl = false;
var replyto = ""; // set here your email;
var userName = string.Empty;
var password = string.Empty;
var port = 25;
var host = "localhost";
userName = "abc"; // setup here the username;
password = "abc"; // setup here the password;
bool.TryParse("true", out useDefaultCredentials); //setup here if it uses defaault credentials
bool.TryParse("true", out enableSsl); //setup here if it uses ssl
int.TryParse("25", out port); //setup here the port
host = "www.google.com"; //setup here the host
using (var mail = new MailMessage(from, to))
{
mail.Subject = subject;
mail.Body = mailbody;
mail.IsBodyHtml = true;
mail.ReplyToList.Add(new MailAddress(replyto, "My Email"));
mail.ReplyToList.Add(from);
mail.DeliveryNotificationOptions = DeliveryNotificationOptions.Delay |
DeliveryNotificationOptions.OnFailure |
DeliveryNotificationOptions.OnSuccess;
using (var client = new SmtpClient())
{
client.Host = host;
client.EnableSsl = enableSsl;
client.Port = port;
client.UseDefaultCredentials = useDefaultCredentials;
if (!client.UseDefaultCredentials && !string.IsNullOrEmpty(userName) &&
!string.IsNullOrEmpty(password))
{
client.Credentials = new NetworkCredential(userName, password);
}
await client.SendMailAsync(mail);
}
}
return true;
}
}
}
MVC5 Resources
Some good online resources about MVC5:
ASP.NET MVC5 : The official Microsoft .NET WebSite
http://www.asp.net/mvc/tutorials/mvc-5
For more examples, follow my blog at
http://joaoeduardosousa.wordpress.com/
Check my other source code:
http://code.msdn.microsoft.com/MVC4-ENTITY-FRAMEWORK-10-e15ef983
http://code.msdn.microsoft.com/ASPNET-MVC-5-Bootstrap-30-622be454
http://code.msdn.microsoft.com/MVC5-Authentication-App-b5200efd
http://code.msdn.microsoft.com/ASPNET-WebAPI-2-Stream-7d96cb70
http://code.msdn.microsoft.com/ASPNET-WebAPI-Basic-Redis-ade42ca7
http://code.msdn.microsoft.com/ASPNET-WebApi-Use-Redis-as-a0d942a3
http://code.msdn.microsoft.com/ASPNET-MVC-connect-with-1f40770f
http://code.msdn.microsoft.com/ASPNET-WebAPI-Enable-Cors-666b88eb
http://code.msdn.microsoft.com/ASPNET-WebAPI-Entity-2f8797a1