Sending Email In ASP.NET MVC - B M SOLUTION
  • Sending Email In ASP.NET MVC

     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.

    1. Start a new MVC project.
    2. Give it some name.
    3. Select ASP.NET template.
    4. Open your Home Controller (or any controller)
    5. 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("jamilmoughal786@gmail.com", "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();  
    }  


  • You might also like

    No comments :

    Post a Comment