Valien
Valien

Reputation: 1145

MVC3 Contact Form not Sending Email After POSTing

I built a simple contact form that works great locally in my test 'mvc1application'. When I transfer the exact code to one of my sites where this form will be I get issues and am really stumped.

Scenario is when a user hits the site it checks to see if they are authenticated already (through an SSO system). If so a cookie is set and they are logged in. If you try to go to the site without logging in you currently get redirected to a 'AccessDenied.cshtml' view. That's no problem at all.

I have since replaced that View with a form (simple contact form) that the user can fill out to email the web master. I get the form to display properly, and on POST it gets a 200 and via Chrome dev tools I see the form content is POSTED. What is not happening is that I don't think my EmailViewModel.cs is being called and processing the form data. So no email is ever sent.

I'm really stumped and here is some of the sample code:

(My AccountController with some parts snipped out...)

[AllowAnonymous]
public ActionResult LogOn(string strEmail, string token)
{
    DepartmentUser departmentuser = db.DepartmentUsers.SingleOrDefault(r => r.UserEmail == strEmail && r.Token == token);
    if (departmentuser != null)
    {
        //verify that the token date  + 1 day >= current datetime
        if (departmentuser.TokenDate.Value.AddDays(1) >= DateTime.Now)
        {
            //if yes, then update to set token = null and datetime = null
            departmentuser.Token = null;
            departmentuser.TokenDate = null;
            db.SaveChanges();

            string userData = departmentuser.DepartmentUserID.ToString() + ":" + departmentuser.DepartmentID.ToString() + ":" + departmentuser.UserName;

            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, departmentuser.UserEmail,
                DateTime.Now, DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes),
                false, userData);
            string hashedTicket = FormsAuthentication.Encrypt(ticket);

            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashedTicket);
            Response.AppendCookie(cookie);
            return Redirect("~/Home");
        }
        else
        {
            return View("RequestForm");

        }
    }
    else
    {
        return View("RequestForm");
    }
}

public ActionResult RequestForm(EmailViewModel emailVM)
{
    if (!ModelState.IsValid)
    {
        return View(emailVM);
    }

    var email = new EmailViewModel
    {

        Name = emailVM.Name,
        EmailAddress = emailVM.EmailAddress,
        InternalTeamName = emailVM.InternalTeamName,
        InternalTeamLeadName = emailVM.InternalTeamLeadName,
        InternalDistEmail = emailVM.InternalDistEmail,
        AverageNumCommsWeekly = emailVM.AverageNumCommsWeekly,
        AverageNumPeopleSentWeekly = emailVM.AverageNumPeopleSentWeekly
    };

    string body = "Name: " + email.Name + "\n"
                + "Email: " + email.EmailAddress + "\n"
                + "Internal Team: " + email.InternalTeamName + "\n"
                + "Internal Team Lead: " + email.InternalTeamLeadName + "\n"
                + "Internal Team Lead Email: " + email.InternalTeamLeadEmail + "\n"
                + "Internal Distribution Email: " + email.InternalDistEmail + "\n"
                + "Average # of Communications Per Week: " + email.AverageNumCommsWeekly + "\n"
                + "Average # of People Emailed Per Week: " + email.AverageNumPeopleSentWeekly;

    MailMessage mail = new MailMessage();

    mail.From = new MailAddress(email.EmailAddress);
    // for production put email in web.config for easy change
    mail.To.Add("[email protected]");
    mail.Subject = "Access Request";
    mail.Body = body;
    mail.IsBodyHtml = true;

    // smtp is local directory in web.config for testing ATM...
    SmtpClient smtp = new SmtpClient();

    smtp.Send(mail);

    mail.Dispose();
    return View("RequestForm");

}

And my EmailViewModel.cs...

namespace MVC.Models
{
    public class EmailViewModel
    {
        [Required]
        public string Name { get; set; }

        [Required]
        [DataType(DataType.EmailAddress)]
        public string EmailAddress { get; set; }

        [Required]
        public string InternalTeamName { get; set; }

        [Required]
        public string InternalTeamLeadName { get; set; }

        [Required]
        public string InternalTeamLeadEmail { get; set; }

        [Required]
        public string InternalDistEmail { get; set; }

        [Required]
        public string AverageNumCommsWeekly { get; set; }

        [Required]
        public string AverageNumPeopleSentWeekly { get; set; }


    }
}

And lastly my Requestform.cshtml view...

@model CorpNewsMgr.Models.EmailViewModel
@{
    ViewBag.Title = "Request Access";
    Layout = "~/Views/Shared/_WideLayoutDenied.cshtml";
}
<p>
    Currently you do not have the required credentials to access the site.
    <br />
    To request more information, or to request permission to access this system, please
    contact:
</p>
<br />
<br />
<div>
    <h3>
        Please fill this form out to request access to the tool.</h3>
    @using (Html.BeginForm())
    {
        @Html.ValidationSummary(true)
        <fieldset>
            <legend>Request Access</legend>
            <div class="editor-label">
                @Html.LabelFor(Model => Model.Name)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(Model => Model.Name)
                @Html.ValidationMessageFor(Model => Model.Name)
            </div>
            <div class="editor-label">
                @Html.LabelFor(Model => Model.EmailAddress)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(Model => Model.EmailAddress)
                @Html.ValidationMessageFor(Model => Model.EmailAddress)
            </div>
            <div class="editor-label">
                @Html.LabelFor(Model => Model.InternalTeamName)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(Model => Model.InternalTeamName)
                @Html.ValidationMessageFor(Model => Model.InternalTeamName)
            </div>
            <div class="editor-label">
                @Html.LabelFor(Model => Model.InternalTeamLeadName)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(Model => Model.InternalTeamLeadName)
                @Html.ValidationMessageFor(Model => Model.InternalTeamLeadName)
            </div>
            <div class="editor-label">
                @Html.LabelFor(Model => Model.InternalTeamLeadEmail)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(Model => Model.InternalTeamLeadEmail)
                @Html.ValidationMessageFor(Model => Model.InternalTeamLeadEmail)
            </div>
            <div class="editor-label">
                @Html.LabelFor(Model => Model.InternalDistEmail)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(Model => Model.InternalDistEmail)
                @Html.ValidationMessageFor(Model => Model.InternalDistEmail)
            </div>
            <div class="editor-label">
                @Html.LabelFor(Model => Model.AverageNumCommsWeekly)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(Model => Model.AverageNumCommsWeekly)
                @Html.ValidationMessageFor(Model => Model.AverageNumCommsWeekly)
            </div>
            <div class="editor-label">
                @Html.LabelFor(Model => Model.AverageNumPeopleSentWeekly)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(Model => Model.AverageNumPeopleSentWeekly)
                @Html.ValidationMessageFor(Model => Model.AverageNumPeopleSentWeekly)
            </div>
            <p>
                <input type="submit" value="Send" />
            </p>
        </fieldset>

    }
</div>
<br />
<p>
    Thank you,<br />

</p>

SO when the page is loaded the form loads fine (yay). I can fill it out and validate it fine (yay). On Submit I get a 200 and POST looks fine (I can see the fields in the POST) but nothing happens. The page reloads as an empty form and I don't see any emails in my pickup folder or anything.

Again, on my local dev test site I can get it to work and route through ok. Here I cannot. I think the issue is with the top of the AccountController and how it's pulling the View but I'm stumped (and tired) from trying to figure this out.

Oh, and it's my 1st large foray into MVC form building from standard WebForms...

Any thoughts?

thanks!

Upvotes: 0

Views: 551

Answers (1)

Garrett Fogerlie
Garrett Fogerlie

Reputation: 4458

I was going to comment, but it ran too long.

You need to post the action that the Requestform.cshtml posts to, also your account controller code is not really needed here. My guess is your hosting environment is shared hosting and there is something preventing your emailing code from functioning.

The first thing you may want to do is if your email code is inside a try catch, temporarily comment our the try catch so it will throw and error. This should at least help give you an idea of what is going on.

The next thing to do is try adding Elmah for mvc3, you can add this via Nuget in Visual Studios. Make sure to use the Elmah for MVC3 one since it will have everything mostly setup for you. This will allow you to see it there are any errors being thrown.

Otherwise without seeing your actual email code I can't be of more help.

Upvotes: 1

Related Questions