如何通过我的控制器通过电子邮件发送我的视图?

时间:2019-07-11 15:01:50

标签: asp.net-mvc

我是ASP.net MVC的初学者,当我想通过电子邮件与控制器发送视图时遇到问题。 我没有到达发送它,我只是到达发送了一些文本

关于我已经尝试过的内容,我将向您展示代码。

(如果我的问题无法理解,请给我我不同的解释)


// Page MailHelper.cs
// The tools for sending mail

        public static void SendMail(string body)
        {
            try
            {
                var mailto = ConfigurationManager.AppSettings["mailto"].Split(';');

                MailMessage mail = new MailMessage();
                mail.IsBodyHtml = true;
                SmtpClient SmtpServer = new SmtpClient(); 

                mail.From = new MailAddress("SendVersionsRobot@trysomething.fr");
                foreach (var m in mailto)   
                    mail.To.Add(m);    
                mail.Subject = "try send Mail";  
                mail.Body = body;     
                SmtpServer.Send(mail);   
            }
            catch (Exception ex)
            {

            }
        }

// Page MailController.cs
using....

namespace MvcMovie.Controllers
{
    public class MailController : Controller
    {
        public ActionResult pageDeTest()
        {
            MailHelper.SendMail(pageDeTest());
            return View();
        }
    }


}


<div id="demo"></div>


<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
    $.getJSON("..\\..\\jsconfig.json", function (data) {
        $('#demo').html(JSON.stringify(data));
    });

    /*console.log("try");*/
</script>


1 个答案:

答案 0 :(得分:0)

当前,我的页面MailController.cs的发展如下:

命名空间MvcMovie.Controllers {     公共类MailController:控制器     {         公共ActionResult pageDeTest()         {             字符串myString = RenderPartialViewToString(MailHelper.SendMail());             MailHelper.SendMail(myString);             返回View();         }

    protected string RenderPartialViewToString(ControllerContext context, string viewName, object model)
    {
        var controller = context.Controller;

        if (string.IsNullOrEmpty(viewName))
            viewName = controller.ControllerContext.RouteData.GetRequiredString("action");

        ViewData.Model = model;

        using (StringWriter sw = new StringWriter())
        {
            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
            ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, ViewData, TempData, sw);
            viewResult.View.Render(viewContext, sw);

            return sw.GetStringBuilder().ToString();
        }
    }