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