如何使用html附件发送电子邮件

时间:2014-08-24 08:06:03

标签: c# .net asp.net-mvc asp.net-mvc-4 email-attachments

ASP.NET / Mono MVC4 C#应用程序。 html文档需要通过邮件作为附件发送。

我试过

        using (var message = new MailMessage("from@somebody.com",
            "to@somebody.com",
            "test",
            "<html><head></head><body>Invoice 1></body></html>"
            ))
        {
            message.IsBodyHtml = true;
            var client = new SmtpClient();
            client.Send(message);
        }

但是html内容出现在邮件正文中。 如何强制html内容显示为电子邮件附件?

更新

我尝试过异常回答,但文档仍然只出现在邮件正文的Windows Mail中。

消息来源显示它包含两部分:

----boundary_0_763719bf-538c-4a37-a4fc-e4d26189b18b
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: base64

----boundary_0_763719bf-538c-4a37-a4fc-e4d26189b18b
Content-Type: text/html; charset=utf-8
Content-Transfer-Encoding: base64

两个部分都具有相同的base64内容。 如何强制html显示为附件?

邮件正文可以为空。

1 个答案:

答案 0 :(得分:4)

如果您想将html作为附件发送,则必须将其添加到message AlternateView中,如图所示

AlternateView htmlView = AlternateView.CreateAlternateViewFromString
               ("<html><head></head><body>Invoice 1></body></html>", null, "text/html");

message.AlternateViews.Add(htmlView);

OR

只需创建一个您要作为附件发送的txtpdfhtml文档,然后执行以下操作: -

message.Attachments.Add(new Attachment(@"c:\inetpub\server\website\docs\test.pdf"));

或者您可以从内存流创建附件(您可以根据需要更改示例代码): -

System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.IO.StreamWriter writer = new System.IO.StreamWriter(ms);
writer.Write("<html><head></head><body>Invoice 1></body></html>");
writer.Flush();
writer.Dispose();

System.Net.Mime.ContentType ct 
            = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Text.Html);
System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, ct);
attach.ContentDisposition.FileName = "myFile.html";

ms.Close();