2016-11-28 59 views
2

希望我能以簡單的方式解釋了我的請求:使用電子郵件發送導致MailKit Razor視圖

在.NET中的核心,我們可以顯示.cshtml視圖,使用View(FileName, Model)發送模型數據之後。

有沒有辦法給Model發送到.cshtml文件,這樣,而不是顯示的結果視圖我得到它的電子郵件使用Mailkit

回答

6

感謝附件Paris Polyzos和他article

我找到了解決方案,所以很喜歡分享它,可能有人會從中獲益,或者改善它。

杉杉:我們需要創建service到Rasor轉換成字符串,代碼Razor2String.cs低於:

using System 
using System.IO; 
using System.Threading.Tasks; 
using Microsoft.AspNetCore.Http; 
using Microsoft.AspNetCore.Mvc; 
using Microsoft.AspNetCore.Mvc.Abstractions; 
using Microsoft.AspNetCore.Mvc.ModelBinding; 
using Microsoft.AspNetCore.Mvc.Razor; 
using Microsoft.AspNetCore.Mvc.Rendering; 
using Microsoft.AspNetCore.Mvc.ViewFeatures; 
using Microsoft.AspNetCore.Routing; 
  
namespace Project.Utilities 
{ 
    public interface IViewRenderService 
    { 
        Task<string> RenderToStringAsync(string viewName, object model); 
    } 
  
    public class ViewRenderService : IViewRenderService 
    { 
        private readonly IRazorViewEngine _razorViewEngine; 
        private readonly ITempDataProvider _tempDataProvider; 
        private readonly IServiceProvider _serviceProvider; 
         public ViewRenderService(IRazorViewEngine razorViewEngine, 
            ITempDataProvider tempDataProvider, 
            IServiceProvider serviceProvider) 
        { 
            _razorViewEngine = razorViewEngine; 
            _tempDataProvider = tempDataProvider; 
            _serviceProvider = serviceProvider; 
        } 
  
        public async Task<string> RenderToStringAsync(string viewName, object model) 
        { 
            var httpContext = new DefaultHttpContext { RequestServices = _serviceProvider }; 
            var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor()); 
  
            using (var sw = new StringWriter()) 
            { 
                var viewResult = _razorViewEngine.FindView(actionContext, viewName, false); 
                if (viewResult.View == null) 
                { 
                    throw new ArgumentNullException($"{viewName} does not match any available view"); 
                } 
  
                var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) 
                { 
                    Model = model 
                }; 
  
                var viewContext = new ViewContext(
                    actionContext, 
                    viewResult.View, 
                    viewDictionary, 
                    new TempDataDictionary(actionContext.HttpContext, _tempDataProvider), 
                    sw, 
                    new HtmlHelperOptions() 
                ); 
  
                await viewResult.View.RenderAsync(viewContext); 
                return sw.ToString(); 
            } 
        } 
    } 
} 

二:我們需要的"preserveCompilationContext": true添加到buildOptions,所以project.json成爲:

{ 
    "version": "1.0.0-*", 
    "buildOptions": { 
    "debugType": "portable", 
    "emitEntryPoint": true, 
    "preserveCompilationContext": true 
    }, 
    "dependencies": { 
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.1", 
    "Microsoft.AspNetCore.Mvc": "1.0.1", 
    "MailKit":"1.10.0" 
    }, 
    "frameworks": { 
    "netcoreapp1.0": { 
     "dependencies": { 
     "Microsoft.NETCore.App": { 
      "type": "platform", 
      "version": "1.0.1" 
     } 
     }, 
     "imports": "dnxcore50" 
    } 
    } 
} 

第三:我們需要的service添加到ConfigureServicesStartup類,使Startup.cs文件變成:

using System; 
using Microsoft.AspNetCore.Builder; 
using Microsoft.AspNetCore.Http; 
using Microsoft.Extensions.DependencyInjection; 
using Project.Utilities; 

public class Startup 
    { 
     public void ConfigureServices(IServiceCollection services) 
     { 
      // Add framework services. 
      services.AddMvc(); 
      // Add application services. 
      services.AddScoped<IViewRenderService, ViewRenderService>(); 
     } 

     public void Configure(IApplicationBuilder app) 
     { 
      app.UseMvc(); 

      app.Run(async (context) => 
      { 
       await context.Response.WriteAsync(
        "Hello World of the last resort. The Time is: " + 
        DateTime.Now.ToString("hh:mm:ss tt")); 
      }); 
     } 
    } 

四:定義Model,像users.cs

namespace myApp 
{ 
    public class users { 
     public string UserId {get; set;} 
     public string UserName {get; set;} 
    } 
} 

第五:創建View模板,在Views文件夾,像Views/Razor2String.cshtml

Hello 
<hr/> 

@{ 
    ViewData["Title"] = "Contact"; 
} 
<h2>@ViewData["Title"].</h2> 
<h3>user id: @Model.UserId</h3> 

第六:Program.cs簡單如下:

using System.IO; 
using Microsoft.AspNetCore.Builder; 
using Microsoft.AspNetCore.Hosting; 

namespace myApp 
{ 
    public class Program 
    { 
     public static void Main(string[] args) 
     { 
      var host = new WebHostBuilder() 
       .UseContentRoot(Directory.GetCurrentDirectory()) 
       .UseKestrel() 
       .UseUrls("http://localhost:50000") 
       .UseStartup<Startup>() 
       .Build(); 
      host.Run(); 
     } 
    } 
} 

第七:主要部分, 'Email.cs':

using System; 
using System.IO; 
using Microsoft.AspNetCore.Mvc; 

using Project.Utilities; 
using System.Threading.Tasks; 

using MailKit.Net.Smtp; // for SmtpClient 
using MimeKit; // for MimeMessage, MailboxAddress and MailboxAddress 

namespace myApp 
{ 
    [Route("api")] 
    public class RenderController : Controller 
    { 
     private readonly IViewRenderService _viewRenderService; 
      public RenderController(IViewRenderService viewRenderService) 
     { 
      _viewRenderService = viewRenderService; 
     } 
      
     [Route("sendEmail")] 
     public async Task sendEmail() 
     { 
      var viewModel = new users 
      { 
       UserId = "cdb86aea-e3d6-4fdd-9b7f-55e12b710f78", 
       UserName = "iggy", 
      }; 
      
      // Get the generated Razor view as String 
      var result = await _viewRenderService.RenderToStringAsync("Razor2String", viewModel); 

      MemoryStream stream = new MemoryStream(); 
      StreamWriter writer = new StreamWriter(stream); 
      writer.Write((String)result); 
      writer.Flush(); 
      stream.Position = 0; 

      var message = new MimeMessage(); 
      message.From.Add(new MailboxAddress("Hasan Yousef", "[email protected]")); 
      message.To.Add(new MailboxAddress("Personal", "[email protected]")); 
      message.Subject = "Email Test"; 
      var bodyBuilder = new BodyBuilder(); 

      bodyBuilder.HtmlBody = @"<div>HTML email body</Div>"; 

      bodyBuilder.Attachments.Add ("msg.html", stream); 

      message.Body = bodyBuilder.ToMessageBody(); 

      using (var client = new SmtpClient()) 
       { 
        client.Connect("smtp.gmail.com", 587); 
        client.AuthenticationMechanisms.Remove("XOAUTH2"); // due to enabling less secure apps access 
       Console.WriteLine("Prepairing the Email"); 
        try{ 
         client.Authenticate("[email protected]", "myPSWD"); 
         Console.WriteLine("Auth Completed"); 
        } 
        catch (Exception e){ 
        Console.WriteLine("ERROR Auth"); 
        } 
        try{ 
         client.Send(message); 
         Console.WriteLine("Email had been sent"); 
        } 
        catch (Exception e){ 
         Console.WriteLine("ERROR"); 
        } 
        client.Disconnect(true); 
       } 
     } 
    } 
} 

如果您需要發送回瀏覽器中的字符串,可以使用:

[Route("returnView")] 
    public async Task<IActionResult> returnView() 
    { 
     var viewModel = new users 
     { 
      UserId = "cdb86aea-e3d6-4fdd-9b7f-55e12b710f78", 
      UserName = "iggy", 
     }; 
  
     // Get the generated Razor view as String 
     var result = await _viewRenderService.RenderToStringAsync("Razor2String", viewModel); 
     return Content(result); 
    } 

如果您需要將結果發送到AJAX請求,您可以使用類似的內容:

public async Task<String> RenderInviteView() 
{ 
. 
. 
. 
return result; 
} 

如果您想要要有單獨的方法來將字符串轉換爲類似GenerateStreamFromString(result)的流,則可以使用using (Stream stream = GenerateStreamFromString(result)){ }