In any web application, we may need to send Email for feedback, for messages, or for any other purpose. In this blog, I will show how to do it step by step.
- Start a new MVC project.
- Give it some name.
- Select ASP.NET template.
- Open your Home Controller (or any controller)
- In Controller, create an ActionResult method SendEmail (you can give it any name).
- public ActionResult SendEmail() {
- return View();
- }
- Add an empty View for this action method and add the following code.
- @ {
- ViewBag.Title = "SendEmail";
- } < h2 > SendEmail < /h2> < br / > < br / > @if(ViewBag.Error != null) { < h2 > @ViewBag.Error < /h2>
- } < form method = "post"
- action = "SendEmail" > < div class = "container" > < span class = "form-control-static" > Receiver: < /span> < input class = "form-control"
- type = "text"
- name = "receiver" / > < br / > < span class = "form-control-static" > Subject: < /span> < input class = "form-control"
- type = "text"
- name = "subject" / > < br / > < span class = "form-control-static" > Message: < /span> < input class = "form-control"
- type = "text"
- name = "message" / > < br / > < input class = "btn btn-primary"
- type = "submit"
- value = "Send" / > < /div> < /form>
- Now, add another action method with the same name and Httppost request as following,
- [HttpPost]
- public ActionResult SendEmail(string receiver, string subject, string message) {
- try {
- if (ModelState.IsValid) {
- var senderEmail = new MailAddress("[email protected]", "Jamil");
- var receiverEmail = new MailAddress(receiver, "Receiver");
- var password = "Your Email Password here";
- var sub = subject;
- var body = message;
- var smtp = new SmtpClient {
- Host = "smtp.gmail.com",
- Port = 587,
- EnableSsl = true,
- DeliveryMethod = SmtpDeliveryMethod.Network,
- UseDefaultCredentials = false,
- Credentials = new NetworkCredential(senderEmail.Address, password)
- };
- using(var mess = new MailMessage(senderEmail, receiverEmail) {
- Subject = subject,
- Body = body
- }) {
- smtp.Send(mess);
- }
- return View();
- }
- } catch (Exception) {
- ViewBag.Error = "Some Error";
- }
- return View();
- }
- Be sure that the strings in the arguments of Httppost method are same with that of name of inputs in the View because with these strings, inputs will be accessed from the View. And, write your password of Gmail Account in the blank space. Emails will be sent using this account.
- Now, save your project. It will look like the following in the browser.
Fill the fields and check for Email. It will work.