Send Event Invitation Emails Using MVC 5 With Code First Approach

Introduction

In this article we will discuss how to send event Invitation emails using MVC 5 with code first approach.

Step 1: Firstly, create one database with table structure like the following which will take users input from UI & save the record in the database.

I have created database name Event_Invitation. Now create table like the following code snippet.

  1. Create Table User_Details  
  2. (  
  3. Id int IDENTITY(1,1) NOT NULL,  
  4. Name varchar(100),  
  5. Mobile varchar(100),  
  6. Email varchar(100),  
  7. City varchar(100)  
  8. Primary Key(Id)  
  9. )  
Step 2: Now create one project in Visual studio 2013 using MVC application from templates.

Now go to solution folder in our project, right click on that, go to Add, New Item, then select ADO.NET Entity Data Model from Data.

Data model

Step 3:
Now click on ADD edmx with the following steps.

Genetate database

Choose connection

test connection

Click next

table

Click on finish. Here we can see our folder structure looks like the following.

model

Step 4: Now first Build our application. Add controller by using entity framework by right click on controller folder,

Controller

Now run the application, you will see the following:

click on create new

Click on Create New & fill the details

Create detail

Click on Create button & you will see the following:

Event

Step 5: Now create another controller as Home. Here in this controller we will write our logic for sending multiple emails to all registered users.

add controller

After creating Home controller add action method & create view for the same by right click on action method.
  1. public ActionResult Index()  
  2. {  
  3.    return View();  
  4. }  
For view take a file input to upload a file & take ViewBag to show message as:
  1. @  
  2. {  
  3.     ViewBag.Title = "Index";  
  4. } < h2 > Index < /h2>@  
  5. using(Html.BeginForm("Index""Home", FormMethod.Post, new  
  6. {  
  7.     enctype = "multipart/form-data"  
  8. }))  
  9. { < label  
  10.     for = "file" > Select Logo  
  11.     for Email Body & automatically emails will send to all < /label> < input type = "file"  
  12.     name = "file"  
  13.     id = "file" / > < br > < input type = "submit"  
  14.     id = "submit" / > < br / >  
  15. }@  
  16. ViewBag.exception  
Create one folder in our solution as Images where we can upload the selected image.

Then write action method which will take a file as input & store this file in our project folder i.e. Images folder.
  1. [HttpPost]  
  2. public ActionResult Index(HttpPostedFileBase file)  
  3. {  
  4.     if (file != null && file.ContentLength > 0)  
  5.     {  
  6.         string str = Path.GetFileName(file.FileName);  
  7.         string path = Path.Combine(Server.MapPath("~/Images"), Path.GetFileName(file.FileName));  
  8.         file.SaveAs(path);  
  9.         Get_Multiple_Email_Ids();  
  10.     }  
  11.     return View();  
  12. }  
Here you will see I have created one method as name Get_Multiple_Email_Ids(); which will get all registered email ids from database.

In this example, I am going to use gmail account to send emails as a response to the registered users with all event details, such as Event Name, Venue, Date Time, Contact Number, Logo including hyper link on that logo.

So first we need add gmail account details in web.config file as:
  1. <add key="Email" value="[email protected]" />  
  2. <add key="Password" value="GmailPassword" />  
  3. <add key="Host" value="smtp.gmail.com" />  
Now add function in controller as,
  1. public void Get_Multiple_Email_Ids()  
  2. {  
  3.     SqlConnection con = new SqlConnection();  
  4.     con.ConnectionString = "Data Source=Rupesh-PC\\SA;Initial Catalog=Event_Invitation;Integrated Security=True";  
  5.     con.Open();  
  6.     SqlCommand cmd = new SqlCommand("select Email from User_Details", con);  
  7.     SqlDataReader read_Email = cmd.ExecuteReader();  
  8.     DataTable dt = new DataTable();  
  9.     dt.Load(read_Email);  
  10.     for (int k = 0; k < dt.Rows.Count; k++)  
  11.     {  
  12.         string strTo = dt.Rows[k]["Email"].ToString();  
  13.         sendEmail(strTo);  
  14.     }  
  15. }  
In above method you will see another method sendEmail(strTo) which will send emails to all.

The following function contains,
  • From which email id we are going to send mail.
  • Email Subject line.
  • Smtp details.
  • Hyper link details & style sheet to our html body of an email.
  • Image attachment code to add an image to out html body of an email.
  • ViewBag which will show success message or failure message on UI.

Very Important: If you are going to use a gmail account then make sure that your account Access for less secure app is ON because we are going to send direct email from our code. The following is the URL to make it ON from Gmail account.

Source app

If this access is off then you will get the following error in ViewBag while sending email.

Index

  1. protected void sendEmail(string strTo)  
  2. {  
  3.     string strFrom = ConfigurationManager.AppSettings["Email"].ToString();  
  4.     string pass = ConfigurationManager.AppSettings["Password"].ToString();  
  5.     string host = ConfigurationManager.AppSettings["Host"].ToString();  
  6.     string strSubject = "FREE Seminar: Getting Started with Azure on X Dec 2015";  
  7.     MailMessage mailMessage = new MailMessage();  
  8.     MailAddress fromAddress = new MailAddress(strFrom);  
  9.     SmtpClient smtpClient = new SmtpClient();  
  10.     smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;  
  11.     smtpClient.Host = host;  
  12.     smtpClient.Port = 25;  
  13.     smtpClient.EnableSsl = true;  
  14.     smtpClient.UseDefaultCredentials = false;  
  15.     NetworkCredential basicCredential = new NetworkCredential(strFrom, pass);  
  16.     smtpClient.Credentials = basicCredential;  
  17.     mailMessage.From = fromAddress;  
  18.     mailMessage.Subject = strSubject;  
  19.     mailMessage.IsBodyHtml = true;  
  20.     // added for style sheet & hyper link  
  21.     string link = "http://c-sharpcorner.com/";  
  22.     string color_Blue = "color:blue";  
  23.     string list_Bold = "font-weight: bold;";  
  24.     // added for image attachment in body  
  25.     var contentID = "Image";  
  26.     var inlineLogo = new Attachment(@"D:\College\MVC\Complete codes\Email_Template\Email_Template_MVC\Email_Template_MVC\Images\logo.png");  
  27.     inlineLogo.ContentId = contentID;  
  28.     inlineLogo.ContentDisposition.Inline = true;  
  29.     inlineLogo.ContentDisposition.DispositionType = DispositionTypeNames.Inline;  
  30.     mailMessage.Attachments.Add(inlineLogo);  
  31.     mailMessage.Body = "<htm><body> <h1 style=\"" + color_Blue + "\">Seminar C# Corner Pune Chapter Meet</h1> <p>Dear Rupesh,</p> <p><strong>We are pleased to invite you to attend the Webinar by C# Corner Pune Chapter on Azure to be held on DD Dec, 2015. It's completely free of cost offline event.</strong></p><ol><li style=\"" + list_Bold + "\">Event Venu: Flat No 5, Spicer College Road,Sangavi, Pune - 27</li><li style=\"" + list_Bold + "\">Event Date: x Dec 2015 </li><li style=\"" + list_Bold + "\">Event Start Time: 9 AM sharp </li><li style=\"" + list_Bold + "\">Conatct Us: Rupesh 9545273748 </li> <ol><p>Thanks</p><br/> <a href=\"" + link + "\"><img src=\"cid:" + contentID + "\"></a> </body></html>";  
  32.     mailMessage.To.Add(strTo);  
  33.     try  
  34.     {  
  35.         smtpClient.Send(mailMessage);  
  36.         ViewBag.exception = "All Emails Send Successfully !!!";  
  37.     }  
  38.     catch (Exception ex)  
  39.     {  
  40.         ViewBag.exception = ex.Message;  
  41.     }  
  42. }  
Now run our application again, select image/logo from the Browse button

Submitt query

Click in Submit Query & you will get the following message: "All Emails Send Successfully !!!"

Send email

Final output i.e. we get an email as follows. If you click on C#Corner logo then it will redirect to C#Corner website.

output

For more information you can download code. Make sure to add your account details in web config file, create your table & change the connection string in controller.

Summary

This article helps to send Event invitational emails on multiple email ids. Here, I used this demo to invite members for C#Corner Chapter Pune Meets, so they can get event details via email with proper detail information, such as contact number, address, Date time, etc.

Hope you enjoyed this one. 

Up Next
    Ebook Download
    View all
    Learn
    View all