ASP MVC:发送电子邮件并返回消息(No Json)

时间:2012-04-16 20:53:15

标签: asp.net-mvc sendmail

我怀疑在ASP.NET MVC 3中完成了一个项目,其中有一个联系表单。它完美的工作问题是,我想发一条消息“电子邮件发送成功!”完成你的提交。我不是在使用Json。什么是最合适的解决方案 谢谢!

代码:

Contato.cshtml `

@model SSInstitucional.ViewModel.ContatoViewModel
 @using System.Web     

<link href="../../Content/themes/SCTecno.css" rel="stylesheet" type="text/css" />

@using (Html.BeginForm("EnviaEmail")) 
{
    @Html.ValidationSummary(true, "")

    <div id ="divContato" style="text-align:left;  margin-left:460px; margin-right:400px; font-family:Verdana;">

            <div id="txtNome" class="editor-label">
                @Html.LabelFor(model => model.Nome)
               <p>
                @Html.TextBoxFor(m => m.Nome, new { id = "Nome", size = 40, maxlength = "60" })
                @Html.ValidationMessageFor(model => model.Nome)
            </div>
            <div id="txtEmail" class="editor-field">
                @Html.LabelFor(model => model.Email)
                <p>
                @Html.TextBoxFor(m => m.Email, new { id = "Email", size = 40, maxlength = "200" })
                @Html.ValidationMessageFor(model => model.Email)
            </div>
            <div  id="txtAssunto"class="editor-label">
               @Html.LabelFor(model => model.Assunto)
                <p>
                @Html.TextBoxFor(m => m.Assunto, new { id = "assunto", size = 40, maxlength = "200" })
                @Html.ValidationMessageFor(model => model.Assunto)
            </div>
            <div id="txtMensagem" class="editor-field">
               @Html.LabelFor(model => model.Mensagem)
               <p>
                @Html.TextAreaFor(model => model.Mensagem, new { id = "mensagem", rows = "10", cols = "50", maxlength = "5000" })
                @Html.ValidationMessageFor(model => model.Mensagem)
            </div>

                <div id="Enviar" onClick="alert('E-mail enviado com sucesso!!')")>
             @SSHtml.SubmitStyledButton("Enviar")
                </div>





   </div>
}

`

ContatoController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SSInstitucional.ViewModel;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Net;


using System.Diagnostics;

namespace SSInstitucional.Controllers
{


    public class ContatoController : Controller
    {
        //
        // GET: /Contato/

        public ActionResult Index()
        {
            return View();
            Debug.WriteLine("Debug Teste");
        }

        [HttpPost]
        public ActionResult Index(ContatoViewModel contatoViewModel)
        {
            string corpo = "Nome: " + contatoViewModel.Nome + "\n" +
                               "E-Mail: " + contatoViewModel.Email + "\n" +
                               "Assunto: " + contatoViewModel.Assunto + "\n\n" +
                               contatoViewModel.Mensagem;

            sendEmail(contatoViewModel.Nome, contatoViewModel.Email, contatoViewModel.Assunto, corpo);

            // return Json ( new { Sucess = true, MessageBox = "Email enviado com sucesso!" });
            // return Json (new { mbox = "E-Mail enviado com sucesso!" });
            return View();

        }

        public ActionResult EnviaEmail()
        {
            return View();
        }


        private void sendEmail(string fromName, string FromEmail, string subject, string body)
        {
            try
            {
                string smtpEmail = null;
                string usuarioEmail = null;
                string senhaEmail = null;
                int smtpPort = 0;
                bool enableSsl = false;

                MailMessage mail = new MailMessage();

                ////set the addresses
                mail.From = new MailAddress(FromEmail, fromName);
                mail.Sender = new MailAddress(FromEmail, fromName);
                mail.ReplyTo = new MailAddress(FromEmail, fromName);

                mail.To.Add(new MailAddress("myname@webmail.net", fromName));

                //set the content
                mail.Subject = subject;
                mail.Body = body;
                mail.Body += "\n\n------------------------------------------";
                mail.Body += "\n\nEmail de origem: " + FromEmail;
                mail.Body += "\n\n\nEmail enviado pelo Fale Conosco do site.";

                //send the message
                //SmtpClient smtp = new SmtpClient(smtpEmail);
                SmtpClient smtp = new SmtpClient("smtp.webmail.net");

                NetworkCredential credenciais = new NetworkCredential("contato@webmail.net", "sss1122");
                smtp.Credentials = credenciais;
                //smtp.Port = 587;
                if (smtpPort > 0)
                    smtp.Port = 25;

                // enable SSL
                if (enableSsl)
                    smtp.EnableSsl = true;

                smtp.Timeout = 120000;

                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;

                smtp.Send(mail);
                {
                    ModelState.Clear();
                    //return mail(new { Message = "E-mail enviado com sucesso!" });
                }

            }
            catch (FormatException erroFormato)
            {
                throw new Exception("Falha ao enviar email. Verifique se seu email foi digitado corretamente.");
            }
            catch (Exception erro)
            {
                throw new Exception("Falha ao enviar email.");


            }
        }



    }

}

2 个答案:

答案 0 :(得分:2)

如果可以使用js,则可以使用MVC Ajax表单。这里有一个例子http://www.hanselman.com/blog/ASPNETMVCPreview4UsingAjaxAndAjaxForm.aspx

您只需要替换

@using (Html.BeginForm("EnviaEmail")) 
{
   ....
}

@using(Ajax.BeginForm("EnviaEmail", new AjaxOptions
                                                      {
                                                              UpdateTargetId = "form_wrapper_id",
                                                              InsertionMode = InsertionMode.Replace
                                                      }))
{
    ...
}

从Action回来一些按摩。此消息将放入ID为“form_wrapper_id”的HTML标记中。如果你不能使用js,Darin Dimitrov的答案是最好的。

答案 1 :(得分:0)

您的表单目前指向EnviaEmail控制器操作。 EnviaEmail控制器操作不执行任何操作。它只重新显示视图。它不会发送任何电子邮件。所以我猜你的原始代码实际上指的是Index POST动作:

@using (Html.BeginForm())
{
    ...    
}

从我在代码中看到的内容,此POST操作会发送一封电子邮件并重新显示相同的视图。因此,一旦发送电子邮件,您就可以在ViewBag中存储一些消息:

[HttpPost]
public ActionResult Index(ContatoViewModel contatoViewModel)
{
    string corpo = "Nome: " + contatoViewModel.Nome + "\n" +
                       "E-Mail: " + contatoViewModel.Email + "\n" +
                       "Assunto: " + contatoViewModel.Assunto + "\n\n" +
                       contatoViewModel.Mensagem;

    sendEmail(contatoViewModel.Nome, contatoViewModel.Email, contatoViewModel.Assunto, corpo);

    ViewBag.Message = "Email sent successfully";
    return View();
}

然后在您的视图中显示以下消息:

<div>@ViewBag.Message</div>