private async Task <string> RenderToStringAsync(string viewName, AbstractEmailModel model) { var httpContext = new DefaultHttpContext { RequestServices = this.serviceProvider }; var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor()); using (var sw = new StringWriter()) { var viewResult = this.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, this.tempDataProvider), sw, new HtmlHelperOptions() ); await viewResult.View.RenderAsync(viewContext); return(sw.ToString()); } }
public async Task <EmailServiceResult> SendEmailAsync(string viewName, AbstractEmailModel model) { try { string message = await this.RenderToStringAsync(viewName, model); SmtpClient client = new SmtpClient(this.smtpConfiguration.Host); client.UseDefaultCredentials = false; client.Credentials = new NetworkCredential(this.smtpConfiguration.Username, this.smtpConfiguration.Password); client.Port = this.smtpConfiguration.Port; client.EnableSsl = this.smtpConfiguration.UseSSL; MailMessage mailMessage = new MailMessage(); mailMessage.From = new MailAddress(this.smtpConfiguration.EmailAddress); mailMessage.To.Add(model.Email); mailMessage.Body = message; mailMessage.IsBodyHtml = true; mailMessage.BodyEncoding = System.Text.Encoding.UTF8; mailMessage.Subject = model.Subject; client.Send(mailMessage); return(new EmailServiceResult { Success = true }); } catch (Exception) { return(new EmailServiceResult { Success = false }); } }