简体   繁体   中英

Sending an email via contact form with System.Net.Mail Asp.Net MVC C#

In my code below I am trying to create a contact form that has the fields first name, last name, email, comment. When the submit button is pressed I need it to send an email to my Gmail address. I've looked at many guides, forums, tips from all over. Most of my code is based on http://ryanbutler.org/content/aspmvcform/documents/aspmvccontactform.pdf and has been modified in areas I thought would help to get this functioning based on other articles I've read.

My environment:

IDE: Visual Studio 2013 Express for Web
Using IIS 8 Express
Deployment will go to Azure
My Os: Windows 8.1

Error Message after clicking submit and filling out the form:

Error. An error occurred while processing your request.

My questions are: Is there anything wrong with my code? Or could the problem lie not with the code but the server IIS Express or another area? I ask this because I've read somewhere that IIS Express does not support SMTP.

The Controller is:

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

namespace MySite.Controllers
{
    public class SendMailerController : Controller
    {
        //
        // GET: /SendMailer/ 
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Contact(ContactModels c)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    MailMessage msg = new MailMessage();
                    SmtpClient smtp = new SmtpClient();
                    msg.To.Add("MyGmailAddress@gmail.com");
                    msg.Subject = "Contact Us";
                    msg.Body = "First Name: " + c.FirstName;
                    msg.Body += "Last Name: " + c.LastName;
                    msg.Body += "Email: " + c.Email;
                    msg.Body += "Comments: " + c.Comment;
                    msg.IsBodyHtml = false;
                    smtp.Host = "smtp.gmail.com";
                    smtp.Port = 25;   
                    smtp.EnableSsl = true;
                    smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                    smtp.UseDefaultCredentials = false; // 
                    smtp.Credentials = new   NetworkCredential("MyGmailAddress@gmail.com", "MyGmailPassword");  
                    smtp.Host = "smtp.gmail.com";
                    smtp.Send(msg);
                    msg.Dispose();

                    return View("Success");
                }
                catch (Exception)
                {
                    return View("Error");
                }    

            }
            return View();

        }
    }
}

My questions are: Is there anything wrong with my code?

Yes, smtp.gmail.com requires secure connection and is not available on port 25. Try this:

using (var client = new SmtpClient("smtp.gmail.com", 587))
{
    client.EnableSsl = true;
    client.UseDefaultCredentials = false;
    client.Credentials = new NetworkCredential("MyGmailAddress", "Your Gmail Password");

    string body = string.Format(
        "First Name: {0}, Last Name: {1}, Email: {2}, Comment: {3}",
        c.FirstName,
        c.LastName,
        c.Email,
        c.Comment
    );
    var message = new MailMessage(
        "sender@gmail.com", 
        "MyGmailAddress@gmail.com", 
        "Contact Us", 
        "mail body"
    );
    message.IsBodyHtml = false;

    client.Send(message);
}

In case this helps others, this is the slightly modified code based on Darin Dimitrov's helpful (and quick) response:

        [HttpPost]
        public ActionResult Contact(ContactModels c)
        {
            string resultMsg = "There was an error submitting your message. Please try again later.";
            if (!ModelState.IsValid)
            {
                return Content(resultMsg);
            }
            if (ModelState.IsValid)
            {
            using (var client = new SmtpClient("smtp.gmail.com", 587))
            {
                client.EnableSsl = true;
                client.UseDefaultCredentials = false;
                client.Credentials = new NetworkCredential("SendersEmail@gmail.com", "ThePassword");


                string body = string.Format(
                    "First Name: {0}\nLast Name: {1}\nEmail: {2}\nComment: {3}",
                    c.FirstName,
                    c.LastName,
                    c.Email,
                    c.Comment
                ); \\In this block I added a new line \n to appear better when I receive the email.

                var message = new MailMessage();
                message.To.Add("RecipientEmail@gmail.com");
                message.From = new MailAddress(c.Email, c.Name);
                message.Subject = String.Format("Contact Request From: {0} ", c.Name);
                message.Body = body;
                message.IsBodyHtml = false;
                try
                {
                    client.Send(message);

                }
                catch (Exception)
                {
                    return View("Error");
                }

            }                

        }
        return View("Success");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM