MVC主页中的Ajax电子邮件表单失败

时间:2016-09-07 02:48:07

标签: ajax asp.net-mvc asp.net-ajax

在我在MVC中创建的Web项目中,我的主页中有一个Ajax电子邮件表单。我希望表单在发送消息之前提示用户,然后不做任何事情或清除表单并通知用户消息的成功传递。相反,提交表单总是会将我发送到一个“页面”,其中包含我发回的失败消息,而不是其他内容。

这是视图的表单部分。

    @using (Ajax.BeginForm("SendEmailJson", new AjaxOptions
    {
        Confirm = "Send email?",
        OnSuccess = "MessageSent",
        OnFailure = "MessageSent"
    }))
    {
        <div class="form-group">
            @Html.Label("Name")
            @Html.TextBox("FromName")
        </div>
        <div class="form-group">
            @Html.Label("Address")
            @Html.TextBox("FromEmail")
        </div>
        <div class="form-group">
            @Html.Label("Message")
            @Html.TextArea("Message", "", 5, 15, new { })
        </div>
        <div class="form-group">
            <input type="submit" value="Send" class="btn btn-default" />
        </div>
    }

然后调用Home控制器中的电子邮件功能:

    [HttpPost]
    public JsonResult SendEmailJson(EMailViewModel model)
    {
        string msg;
        if (ModelState.IsValid)
        {
            bool suc = SendEmailMessage(model);
            msg = suc ? "Message sent" : "Error sending message. Please try again";
        }
        else
            msg = "An error occurred in the submission of this message.  Please try again.";
        return Json(msg);
    }

    private bool SendEmailMessage(EMailViewModel model)
    {
        try
        {
            var body = "Email from: {0} ({1})\n\nMessage:\n{2}";
            var msg = new MailMessage();
            msg.To.Add(new MailAddress("dummyMailAddress@address.net"));
            msg.From = new MailAddress(model.FromEmail);
            msg.Subject = "Contact from " + model.FromEmail + " through MyWebSiteName";
            msg.Body = string.Format(body, model.FromName, model.FromEmail, model.Message);
            using (var smtp = new SmtpClient())
            {
                smtp.Send(msg);
            }
        }
        catch(Exception)
        {
            return false;
        }
        return true;
    }

该模型是一个非常简单的模型:

public class EMailViewModel
{
    [Required]
    [Display(Name = "Name")]
    public string FromName { get; set; }
    [Required]
    [Display(Name = "Address")]
    public string FromEmail { get; set; }
    [Required]
    [Display(Name = "Message")]
    [DataType(DataType.MultilineText)]
    public string Message { get; set; }
}

我不知道为什么程序会失败,但是我让一些人等了一段时间,这是最后一块拼图。请帮忙。

编辑:关于SMTP设置,我在Web.config文件中有这个:

  <system.net>
    <mailSettings>
      <smtp from="dummyAddress@gmail.com">
        <network host="smtp.gmail.com"
                 port="587"
                 userName="dummyAddress@gmail.com"
                 password="dummyPW"
                 enableSsl="true" />
      </smtp>
    </mailSettings>
  </system.net>

当我弄清楚如何发送电子邮件时,我将相同的配置数据放入一个小型测试项目中,并且发送的电子邮件没有问题。但是,在我的主要真实项目中,这些设置对函数没有任何影响,总是无法发送消息,并且仅将消息发送到新页面,而不是给我弹出显示失败消息的弹出窗口。

1 个答案:

答案 0 :(得分:0)

我发现您在发送电子邮件时遗漏了SendEmailMessage初始化SmtpClient方法中的一些重要设置,这里有一些改进:

private bool SendEmailMessage(EMailViewModel model)
{
    try
    {
        var body = "Email from: {0} ({1})\n\nMessage:\n{2}";
        var msg = new MailMessage();
        msg.To.Add(new MailAddress("dummyMailAddress@address.net"));
        msg.From = new MailAddress(model.FromEmail);
        msg.Subject = "Contact from " + model.FromEmail + " through MyWebSiteName";
        msg.Body = string.Format(body, model.FromName, model.FromEmail, model.Message);
        using (var smtp = new SmtpClient())
        {
            //--- add these lines to define your e-mail provider
            smtp.DeliveryMethod = SmtpDeliveryMethod.Network;

            // set your SMTP server address here
            smtp.Host = "smtp.server.net"; 

            // use port number depending on your server SMTP port, e.g. 25, 465, 587, 2525
            smtp.Port = 587;

            // provide username & password for email access
            smtp.Credentials = new NetworkCredential("serverusername", "serverpassword");

            // additionally, enable SSL if your email server supports secure connection
            smtp.EnableSsl = true;
            //--- end of added lines

            smtp.Send(msg);
        }
    }
    catch(Exception)
    {
        return false;
    }
    return true;
}

如果您在本地服务器上有配送目录配置,请将SmtpDeliveryMethod.Network更改为SmtpDeliveryMethod.PickupDirectoryFromIis

欢迎任何建议。