tags:

views:

591

answers:

4

I'm sending mail from my C# Application, using the SmtpClient. Works great, but I have to decide if I want to send the mail as Plain Text or HTML. I wonder, is there a way to send both? I think that's called multipart.

I googled a bit, but most examples essentially did not use SmtpClient but composed the whole SMTP-Body themselves, which is a bit "scary", so I wonder if something is built in the .net Framework 3.0?

If not, is there any really well used/robust Third Party Library for sending e-Mails?

+6  A: 

What you want to do is use the AlternateViews property on the MailMessage

http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.alternateviews.aspx

Nick Berardi
+1  A: 

The MSDN Documentation seems to miss one thing though, I had to set the content type manually, but otherwise, it works like a charm :-)

MailMessage msg = new MailMessage(username, nu.email, subject, body);
msg.BodyEncoding = Encoding.UTF8;
msg.SubjectEncoding = Encoding.UTF8;

AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlContent);
htmlView.ContentType = new System.Net.Mime.ContentType("text/html");
msg.AlternateViews.Add(htmlView);
Michael Stum
+1 Cancelled out that down vote because this was useful to me.
Jim
+1  A: 

Just want to add that you can use defined constants MediaTypeNames.Text.Html and MediaTypeNames.Text.Plain instead of "text/html" and "text/plain", which is always a preferable way. It's in System.Net.Mime namespace.

So in the example above, it would be:

AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlContent, null, MediaTypeNames.Text.Html);
A: 

I'm just going to put a note here for anyone that's having problems and finds their way to this page - sometimes, Outlook SMTP servers will reconvert outgoing email. If you're seeing your plain-text body vanish entirely, and nothing but base64-encoded attachments, it might be because your server is reencoding the email. Google's SMTP server does not reencode email - try sending through there and see what happens.

Aric TenEyck