How to send email with html attachment

て烟熏妆下的殇ゞ 提交于 2019-12-10 10:35:28

问题


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

I tried

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

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

Update

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

and

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

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

Message body can be empty.


回答1:


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

OR

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

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


来源:https://stackoverflow.com/questions/25469751/how-to-send-email-with-html-attachment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!