Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Send both HTML and Text email - most elegant?

Tags:

Is is best practice to send both HTML and Text email?

If I only send HTML what are the dangers?

I'm thinking something like this below from

http://johnnycoder.com/blog/2009/04/15/net-mailmessage-linkedresources-alternateviews-and-exceptions/

try {     // Assign a sender, recipient and subject to new mail message     MailAddress sender =         new MailAddress("[email protected]", "Sender");      MailAddress recipient =         new MailAddress("[email protected]", "Recipient");      MailMessage m = new MailMessage(sender, recipient);     m.Subject = "Test Message";      // Define the plain text alternate view and add to message     string plainTextBody =         "You must use an email client that supports HTML messages";      AlternateView plainTextView =         AlternateView.CreateAlternateViewFromString(             plainTextBody, null, MediaTypeNames.Text.Plain);      m.AlternateViews.Add(plainTextView);      // Define the html alternate view with embedded image and     // add to message. To reference images attached as linked     // resources from your HTML message body, use "cid:contentID"     // in the <img> tag...     string htmlBody =         "<html><body><h1>Picture</h1><br>" +         "<img src=\"cid:SampleImage\"></body></html>";      AlternateView htmlView =         AlternateView.CreateAlternateViewFromString(             htmlBody, null, MediaTypeNames.Text.Html);      // ...and then define the actual LinkedResource matching the     // ContentID property as found in the image tag. In this case,     // the HTML message includes the tag     // <img src=\"cid:SampleImage\"> and the following     // LinkedResource.ContentId is set to "SampleImage"     LinkedResource sampleImage =         new LinkedResource("sample.jpg",             MediaTypeNames.Image.Jpeg);     sampleImage.ContentId = "SampleImage";      htmlView.LinkedResources.Add(sampleImage);      m.AlternateViews.Add(htmlView);      // Finally, configure smtp or alternatively use the     // system.net mailSettings     SmtpClient smtp = new SmtpClient           {               Host = "smtp.example.com",               UseDefaultCredentials = false,               Credentials =                   new NetworkCredential("username", "password")           };      //<system.net>     //    <mailSettings>     //        <smtp deliveryMethod="Network">     //            <network host="smtp.example.com"     //              port="25" defaultCredentials="true"/>     //        </smtp>     //    </mailSettings>     //</system.net>      smtp.Send(m); } catch (ArgumentException) {     throw new         ArgumentException("Undefined sender and/or recipient."); } catch (FormatException) {     throw new         FormatException("Invalid sender and/or recipient."); } catch (InvalidOperationException) {     throw new         InvalidOperationException("Undefined SMTP server."); } catch (SmtpFailedRecipientException) {     throw new SmtpFailedRecipientException(         "The mail server says that there is no mailbox for recipient"); } catch (SmtpException ex) {     // Invalid hostnames result in a WebException InnerException that     // provides a more descriptive error, so get the base exception     Exception inner = ex.GetBaseException();     throw new SmtpException("Could not send message: " + inner.Message); } 
like image 777
Dave Mateer Avatar asked Aug 11 '10 07:08

Dave Mateer


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.


2 Answers

I would say that, in today's world, the "best-practice" approach would be to ensure that you send your message as both plain text and HTML (if you really want to send HTML email messages).

Oh, and make sure you do actually send the content in the plain text view, rather than a single sentence saying "You must use an email client that supports HTML messages". Google Mail takes this approach, and it seems to work perfectly, allowing "rich" views on full-fledged PC clients, whilst also allowing "minimal" views on more restricted devices (i.e. Mobile/Cell phones).

If you want to take a purist's view, you wouldn't be sending HTML emails at all, nor would you ever "attach" a binary file to an email. Both corruptions of the original email standard, which was only ever originally intended for plain text. (See some people's opinions of this here and here)

However, in the pragmatic modern-day real world, HTML email is very real, and very acceptable. The primary downside to sending HTML email is whether the recipient will see the email in the way that you intended them to see it. This is much the same problem that web designers have battled with for years; getting their websites to look "just right" in all possible browsers (although it's significantly easier today than it was many years ago).

Similar to ensuring that a website functions correctly without requiring Javascript, by sending your emails as both HTML and Plain Text, you'll ensure that your emails degrade gracefully so that people reading their emails on (for example) small mobile devices (something that's becoming more and more prevalent these days - and which may or may not be capable of rendering a complete HTML email) can still read your email content without issue.

like image 132
CraigTP Avatar answered Sep 27 '22 17:09

CraigTP


If you only send HTML, then anyone reading email on a text-only device will have trouble.

For example, I suspect many low-end mobile devices are capable of reading email but not displaying full HTML.

I would say it's best practice to either send text-only, or text and HTML.

I don't see why you're catching a bunch of exceptions only to rethrow the same exception type with a different message, by the way - the original message may well be more descriptive.

like image 31
Jon Skeet Avatar answered Sep 27 '22 17:09

Jon Skeet