【问题标题】:How to send email with html attachment如何发送带有 html 附件的电子邮件
【发布时间】:2014-08-24 08:06:03
【问题描述】:

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显示为附件?

邮件正文可以为空。

【问题讨论】:

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


    【解决方案1】:

    如果你想将html作为附件发送,那么你必须将它添加到messageAlternateView,如图所示

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

    只需创建要作为附件发送的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();
    

    【讨论】:

    • 这会导致编译错误 Argument 1: cannot convert from 'System.Net.Mail.AlternateView' to 'string' 在行 message.Attachments.Add(new Attachment(htmlView));
    • 我试过了,但附件没有出现,html 内容仍然出现在 Windows Mail 邮件正文中。我更新了问题。
    • @Andrus..你为什么不创建一个 txt 或 pdf 文档并将其作为附件发送??
    • 发票由设计师以 html 格式创建。 Txt 格式不保留格式。如 stackoverflow.com/questions/25469597/… 中所述,将 html 转换为 pdf 不会在 Mono 中。由于输入已经是 html,我正在寻找一种将 html 文档作为附件发送的方法,以便它们可以以原封不动的形式打印、保存和转发。
    • 代码正在Web服务器中运行,可能有多个并发请求。我正在寻找一种解决方案,而无需在磁盘中为每封电子邮件创建临时文件。如果创建临时文件是最好的解决方案,发送后如何从磁盘中删除附件文件?是否可以在内存中创建附件文件作为来自字符串的流并使用new Attachment(stream, "file.pdf")
    猜你喜欢
    • 1970-01-01
    • 2013-11-26
    • 1970-01-01
    • 2011-10-05
    • 2015-10-27
    • 2015-09-09
    相关资源
    最近更新 更多