在ASP.NET MVC中,您可以使用Razor引擎将视图转换为字符串,然后将其用作电子邮件发送。以下是一个简单的示例:
EmailTemplate.cshtml
:<!DOCTYPE html>
<html>
<head>
<title>电子邮件模板</title>
</head>
<body>
<h1>@Model.Subject</h1>
<p>@Model.Content</p>
</body>
</html>
RazorEngine
将视图转换为字符串:using System.Web.Mvc;
using RazorEngine;
using RazorEngine.Configuration;
using RazorEngine.Templating;
public class EmailController : Controller
{
public ActionResult SendEmail()
{
// 配置 RazorEngine
var config = new TemplateServiceConfiguration
{
BaseTemplateType = typeof(HtmlSupportTemplateBase<>),
Namespaces = new[] { "System.Web.Mvc" }
};
var service = RazorEngineService.Create(config);
// 创建视图模型
var viewModel = new EmailViewModel
{
Subject = "Hello World",
Content = "This is a test email."
};
// 将视图模板转换为字符串
var emailBody = service.RunCompile("EmailTemplate.cshtml", typeof(EmailViewModel), viewModel);
// 发送电子邮件
var emailService = new EmailService();
emailService.SendEmail("recipient@example.com", "Hello World", emailBody);
return View();
}
}
using System.Net.Mail;
public class EmailService
{
public void SendEmail(string to, string subject, string body)
{
var from = "sender@example.com";
var password = "your_password";
using (var mail = new MailMessage(from, to))
{
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
smtp.Host = "smtp.example.com";
smtp.Port = 587;
smtp.Credentials = new System.Net.NetworkCredential(from, password);
smtp.EnableSsl = true;
smtp.Send(mail);
}
}
}
}
Web.config
中配置电子邮件发送服务器和凭据: <system.net>
<mailSettings>
<smtp from="sender@example.com">
<network host="smtp.example.com" port="587" userName="sender@example.com" password="your_password" enableSsl="true" />
</smtp>
</mailSettings>
</system.net>
</configuration>
这样,您就可以使用ASP.NET MVC中的视图模板作为电子邮件发送的内容。
领取专属 10元无门槛券
手把手带您无忧上云