0

I made a contact form it has no error but it is not sending email which is main purpose of my page? I am sending email using SMTP gmail. Password is hidden in this code please change that before you try. I am so confused why it isn't working.I have tried a lot but all in vain. I am working in MVC 5 i think there is problem related to it.

                //Model class code starts...........................................

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

            namespace Contacts.Models
            {
                public class Contact
                {
                    [Required]

                    [Display(Name = "Name *")]

                    public string Name { get; set; }

                    [Required]

                    [DataType(DataType.EmailAddress)]

                    [Display(Name = "Email address *")]

                    public string Email { get; set; }

                    [DataType(DataType.PhoneNumber)]

                    [Display(Name = "Phone Number")]

                    public string Phone { get; set; }

                    [Required]

                    [Display(Name = "Message *")]

                    public string Body { get; set; }

                    public DateTime SentDate { get; set; }

                    public string IP { get; set; }



                    public string BuildMessage()
                    {

                        var message = new StringBuilder();

                        message.AppendFormat("Date: {0:yyyy-MM-dd hh:mm}\n", SentDate);

                        message.AppendFormat("Email from: {0}\n", Name);

                        message.AppendFormat("Email: {0}\n", Email);

                        message.AppendFormat("Phone: {0}\n", Phone);

                        message.AppendFormat("IP: {0}\n", IP);

                        message.AppendFormat("Message: {0}\n", Body);

                        return message.ToString();

                    }
                }
            }

            Model class code end .............................

            Controller class code starts .............................

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



            namespace Contacts.Controllers
            {
                public class ContactController : Controller
                {
                    public ActionResult Index()
                    {

                        ViewBag.Success = false;

                        return View(new Contact());

                    }

                    [HttpPost]

                    public ActionResult Index(Contact contact)
                    {

                        ViewBag.Success = false;

                        {
                            try
                            {

                                if (ModelState.IsValid)
                                {

                                    // Collect additional data;

                                    contact.SentDate = DateTime.Now;

                                    contact.IP = Request.UserHostAddress;



                                    SmtpClient smtpClient = new SmtpClient();
                                    smtpClient.UseDefaultCredentials = false;
                                    smtpClient.Credentials = new System.Net.NetworkCredential
                                    ("tehmina.diya@gmail.com", "********");

             smtpClient.EnableSsl = true;

                                    MailMessage mail = new MailMessage();
                                    mail.From = new MailAddress("tehmina.diya@gmail.com"); // From
                                    mail.To.Add(new MailAddress("tehmina.diya@gmail.com")); // To

                                    mail.Subject = "Your email subject"; // Subject
                                    mail.Body = contact.BuildMessage();



                                    contact.BuildMessage(); // Body
                                    ViewBag.Success = true;
                                    smtpClient.Send(mail);
                                }  

                            }

                            catch (Exception e)
                            {
                               Response.Write("Success");

                            }
                        }



                        return View();

                    }

                }
            }
             Controller class code ends .............................

            View class code Starts.............................

            @model  Contacts.Models.Contact

            @{

                ViewBag.Title = "Contact Page";

            }

            <h2> Contact Page</h2>

            <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>

            <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>

            @Html.ValidationSummary(true, "Sending message was unsuccessful. Please correct the errors and try again.")

            @if (ViewBag.Success)
            {

                <h3>Your message was successfully sent!</h3>

            }

            @using (Html.BeginForm())
            {

                <div>

                    <fieldset>

                        <legend>Contact Information</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.Email)

                        </div>

                        <div class="editor-field">

                            @Html.TextBoxFor(model => model.Email)

                            @Html.ValidationMessageFor(model => model.Email)

                        </div>

                        <div class="editor-label">

                            @Html.LabelFor(model => model.Phone)

                        </div>

                        <div class="editor-field">

                            @Html.TextBoxFor(model => model.Phone)

                            @Html.ValidationMessageFor(model => model.Phone)

                        </div>

                        <div class="editor-label">

                            @Html.LabelFor(model => model.Body)

                        </div>

                        <div class="editor-field">

                            @Html.ValidationMessageFor(model => model.Body)

                            <br />

                            <textarea rows="10" cols="60" name="Body"></textarea>

                        </div>

                        <p>

                            <input type="submit" value="Send" />

                        </p>

                    </fieldset>

                </div>

            }
            //View class ends....................

1 Answers1

0

Here is a great link in stackoverflow that deals with smtp and gmail.

Sending email through Gmail SMTP server with C#

Anyway, I got your code to work. There were several minor errors in your MVC code.

In your controller, in the catch block, you have

    catch (Exception e)
    {
       Response.Write("Success");
    }

Change this to

    catch (Exception e)
    {
       ModelState.AddModelError("",e.Message);

    }

This adds the error you receive back from gmail to your model state. The catch block catches errors, not success!

Then in your view, you have the following line of code

    @Html.ValidationSummary(true, "Sending message was unsuccessful. Please correct the errors and try again.")

Change this to:

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

This will display the error message that you will catch in the catch block if transmission fails.

Now, go to your controller and BEFORE the following line

    smtpClient.Send(mail)

and add the following code

    smtpClient.Host = "smtp.gmail.com";
    smtpClient.Port = 587;
    smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
    smtpClient.Timeout = 20000;

so that it looks like this

    smtpClient.Host = "smtp.gmail.com";
    smtpClient.Port = 587;
    smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
    smtpClient.Timeout = 20000;
    smtpClient.Send(mail)

It should work. if you start to get timeouts, then just increase the timeout in the code.

Community
  • 1
  • 1
alikuli
  • 526
  • 6
  • 18