答案在这里:http ://social.msdn.microsoft.com/Forums/en/netfxnetcom/thread/c65502fa-955e-4fa1-b409-238bbb677df7
我认为您缺少的主要内容是 LinkedResource 上的 MIME 内容类型。myMagic.css:
body {
background-color: rgb(240,240,240);
font-family: Verdana,Arial,Helvetica,Sans-serif;
font-size: 10pt;
}
h2 {
background-color: rgb(255,255,128);
color: rgb(255,0,0);
}
p {
background-color: rgb(0,0,255);
color: rgb(0,255,0);
font-style: italic;
}
程序.cs:
using System.Net.Mail;
using System.Net.Mime;
namespace MailMessageHTML
{
class Program
{
private static MailMessage ConstructMessage(string from, string to, string subject)
{
const string textPlainContent =@"You need a HTML-capable mail agent to read this message.";
const string textHtmlContent =@"<html><head><link rel='stylesheet' type='text/css' href='cid:myMagicStyle' />
</head>
<body>
<h2>Hello world!</h2>
<p>This is a test HTML e-mail message.</p>
</body>
</html>
";
MailMessage result = new MailMessage(from, to, subject, textPlainContent);
LinkedResource cssResource = new LinkedResource("myMagic.css", "text/css");
//NOTE: Message encoding adds the surrounding <> on this Id cssResource.ContentId =myMagicStyle";
cssResource.TransferEncoding = TransferEncoding.SevenBit;
AlternateView htmlBody = AlternateView.CreateAlternateViewFromString( textHtmlContent , new ContentType("text/html"));
htmlBody.TransferEncoding = TransferEncoding.SevenBit;
htmlBody.LinkedResources.Add(cssResource);
result.AlternateViews.Add(htmlBody);
return result;
}
static void Main(string[] args)
{
MailMessage foo = ConstructMessage(
"sender@foo.com"
,"recipient@bar.com"
, "Test HTML message with style."
);
SmtpClient sender = new SmtpClient();
sender.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
sender.PickupDirectoryLocation = @"...\MailMessageHTML\bin\Debug\";
sender.Send(foo);
}
}
}
注意 1:我在上面的消息部分中指定了 TransferEncoding.SevenBit。您通常不会在生产环境中执行此操作 - 我只在此处执行此操作,因此您可以使用记事本读取生成的 .eml 文件以查看生成的内容。
注意 2:许多邮件代理不支持在邮件部分中链接的样式表。一种更可靠的方法可能是使用内联样式(即:HTML 消息正文中的内联 ... 块)。
祝你好运,
这个答案来自:http ://social.msdn.microsoft.com/Forums/en/netfxnetcom/thread/c65502fa-955e-4fa1-b409-238bbb677df7