如何使用HTML附件发送电子邮件 [英] How to send email with html attachment

查看:140
本文介绍了如何使用HTML附件发送电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ASP.NET /单声道MVC4 C#应用程序。 HTML文档需要由邮件作为附件发送。

ASP.NET / Mono MVC4 C# application. html documents needs to be sent by a-mail as attachment.

我试过

        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内容显示为电子邮件附件?

But html content appears in message body. How to force html content to appear as e-mail attachment ?

更新

我试过异常的答案,但文件仍显示在Windows邮件在邮件正文只。

I tried Exception answer but document still appears in Windows Mail in message body only.

消息源表明,它包含两部分:

Message source shows that it contains two parts:

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

Both parts have same base64 content. How to force html to appear as attachment?

消息体可以是空的。

推荐答案

如果您想发送HTML作为附件,那么你必须将其添加到的消息 AlternateView

If you want to send html as attachment then you have to add it in message AlternateView as shown

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

message.AlternateViews.Add(htmlView);

只要创建一个 TXT PDF HTML 您要发送作为附件,做的文件: -

Just create a txt or pdf or html document which you want to send as attachment and do as :-

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

也可以创建附件从内存流为(样品code您可以按照您的要求更改): -

OR you can create attachment from memory stream as(sample code you can change as per your requirement) :-

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();

这篇关于如何使用HTML附件发送电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆