Valip
Valip

Reputation: 4610

ASP.NET MVC3 send email using SMTP

I've implemented a code that should allow me to send email to gmail from my web application and I can't figure out what is wrong with it...

When I press the "Submit" button nothing happens, there are no errors. I also added breakpoints in my controller but they are not fired...

Here is my code:

Model:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.ComponentModel.DataAnnotations;

namespace TripPlanner.Models
{
    public class EmailFormModel
    {
        [Required]
        [StringLength(20, MinimumLength = 5)]
        public string Name { get; set; }
        [Required]
        [DataType(DataType.EmailAddress)]
        public string Email { get; set; }
        [Required]
        public string Subject { get; set; }
        [Required]
        public string Message { get; set; }
    }
}

View:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<TripPlanner.Models.EmailFormModel>" %>
<% using (Html.BeginForm()) {%>
    <form method="post">
        <%: Html.ValidationSummary("Please correct the errors and try again.") %>
        <p>Name: </p>
        <%: Html.TextBoxFor(m => m.Name)%>
        <p>Email: </p>
        <%: Html.TextBoxFor(m => m.Email)%>
        <p>Subject: </p>
        <%: Html.TextBoxFor(m => m.Subject)%>
        <p>Message: </p>
        <%: Html.TextBoxFor(m => m.Message)%>
        <input type ="submit" value ="Send" />
    </form>
<% } %>

Controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;
using System.Web.Mvc;
using System.IO;
using System.Net;
using TripPlanner.Models;

namespace TripPlanner.Controllers
{
    public class SendMailerController: Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Index(EmailFormModel vm)
        {
            if(ModelState.IsValid)
            {
                try
                {
                    MailMessage msz = new MailMessage();
                    msz.From = new MailAddress(vm.Email);//Email which you are getting from contact us page 
                    msz.To.Add("[email protected]");//Where mail will be sent 
                    msz.Subject = vm.Subject;
                    msz.Body = vm.Message;
                    SmtpClient smtp = new SmtpClient();

                    smtp.Host = "smtp.gmail.com";
                    smtp.Port = 587;
                    smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "my_valid_pass");
                    smtp.EnableSsl = true;
                    smtp.Send(msz);

                    ModelState.Clear();
                }
                catch(Exception ex )
                {
                    ModelState.Clear();
                }              
            }

            return View();
        }
        public ActionResult Error()
        {
            return View();
        }
    }
}

Upvotes: 0

Views: 615

Answers (2)

Banwari Yadav
Banwari Yadav

Reputation: 506

<% using (Html.BeginForm("Index", "SendMailer", FormMethod.Post)) {%>
<form method="post">
    <%: Html.ValidationSummary("Please correct the errors and try again.") %>
    <p>Name: </p>
    <%: Html.TextBoxFor(m => m.Name)%>
    <p>Email: </p>
    <%: Html.TextBoxFor(m => m.Email)%>
    <p>Subject: </p>
    <%: Html.TextBoxFor(m => m.Subject)%>
    <p>Message: </p>
    <%: Html.TextBoxFor(m => m.Message)%>
    <input type ="submit" value ="Send" />
</form>

Please change your begin form syntax, you need to specify the action and controller name on which you want to post form data.

Upvotes: 1

user1666620
user1666620

Reputation: 4808

At least one of your problems is that you need to tell the SMTP client to not use your windows credentials before you provide the username and password of the gmail account.

Add

smtp.UseDefaultCredentials = false;

above this line of code (NOT after).

smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "my_valid_pass");

The other obvious problem is that you really need to do something useful in your catch block - right now you are actively sabotaging your efforts by swallowing the exception.

You need to log the exception, or at the very least throw it. Removing the try/catch altogether would also be better than what you are doing right now.

Also, gmail will ignore whatever value you place in MailMessage.From property as it does not allow you to send emails as other users.

Upvotes: 0

Related Questions