简体   繁体   English

通过与System.Net.Mail Asp.Net MVC C#的联系表发送电子邮件

[英]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. 按下“提交”按钮后,我需要它向我的Gmail地址发送电子邮件。 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. 我的大部分代码都基于http://ryanbutler.org/content/aspmvcform/documents/aspmvccontactform.pdf ,并已在我认为将有助于根据我已阅读的其他文章实现此功能的领域进行了修改。

My environment: 我的环境:

IDE: Visual Studio 2013 Express for Web IDE:适用于Web的Visual Studio 2013 Express
Using IIS 8 Express 使用IIS 8 Express
Deployment will go to Azure 部署将转到Azure
My Os: Windows 8.1 我的操作系统: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? 还是问题可能不在于代码,而是服务器IIS Express或其他区域? I ask this because I've read somewhere that IIS Express does not support SMTP. 我问这是因为我读过某个地方IIS Express不支持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: 是的, smtp.gmail.com需要安全连接,并且在端口25上不可用。请尝试以下操作:

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: 如果这对其他人有帮助,这是基于Darin Dimitrov的有用(快速)响应的稍微修改的代码:

        [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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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