我想将包含html标签的文本作为电子邮件发送给用户。
我尝试使用HttpUtility.HtmlDecode
解码html:
string subject = "email Subject";
_emailService.SendEmail(subject, HttpUtility.HtmlDecode(post.Body), "info@myserver.com",
"title", subscription.EmailAddress,
subscription.EmailAddress);
这是SendEmail
类中的MailService
:
public void SendEmail(string subject, string body,
string fromAddress, string fromName, string toAddress, string toName,
string replyTo = null, string replyToName = null,
IDictionary<string, string> headers = null)
{
var message = new MailMessage();
//from, to, reply to
message.From = new MailAddress(fromAddress, fromName);
message.To.Add(new MailAddress(toAddress, toName));
if (!String.IsNullOrEmpty(replyTo))
{
message.ReplyToList.Add(new MailAddress(replyTo, replyToName));
}
//content
message.Subject = subject;
message.Body = body;
message.IsBodyHtml = true;
//headers
if (headers != null)
foreach (var header in headers)
{
message.Headers.Add(header.Key, header.Value);
}
try
{
var client = new SmtpClient("mail.myserver.com", 25)
{
Credentials = new NetworkCredential("info@myserver.com", "myEmailPassword"),
EnableSsl = false
};
client.Send(message);
//send email
}
catch (Exception exc)
{
logger.Error(exc.Message);
}
}
但是我的用户收到一封包含纯HTML标记代码的电子邮件。 如何发送HTML文本作为呈现在用户邮箱上的电子邮件?
答案 0 :(得分:0)
以下是我使用邮政(http://aboutcode.net/postal/)从控制器发送电子邮件的方式:
[ValidateInput(false)]
public void SendFailureEmail()
{
var email = new EmailTemplateModel
{
ViewName = "~/Views/Emails/Template.cshtml",
FromAddress = "sender@address.com",
EmailAddress = "customer@address.com",
Subject = "Task 1",
SingleDate = DateTime.Now,
Description = "Hello World",
};
email.Send();
}
EmailTemplateModel:
public class EmailTemplateModel : Email
{
public string FromAddress { get; set; }
public string EmailAddress { get; set; }
public string Subject { get; set; }
public string Description { get; set; }
public DateTime SingleDate { get; set; }
}
我使用此模板来创建电子邮件的HTML元素:
@model App.Models.EmailTemplateModel
@using App.Utilities;
From: @Model.FromAddress
To: @Model.EmailAddress
Subject : @Model.Subject
<table style="width: 500px;">
<tbody>
<tr>
<td>
Date:
</td>
<td>
@Model.SingleDate
</td>
</tr>
<tr>
<td>
Description:
</td>
<td>
@Model.Description
</td>
</tr>
</tbody>
</table>