Share This!

Thursday, August 29, 2013

MailMessage to Text

This simple class exposes a static method to take a MailMessage object and represent it as a block of text.  I ran into this because when an emailer program I wrote started getting error messages, the only thing I got in the error log was

Failure sending mail. 

 So - to track the problem, I wanted to quickly see what the mailmessage looked like and include it in my error notifications.

Here is the class

using System.Collections.Generic;
using System.Net.Mail;
using System.Text;

namespace mailmessage_to_text
    class MailtoText
        private static string MailAddresstoString(MailAddress addy)
            //"Russ Jansen" <>
            string answer = "";
            if (addy != null)
                if (string.IsNullOrEmpty(addy.DisplayName))
                    answer = string.Format("<{0}>", addy.Address);
                    answer = string.Format("\"{1}\" <{0}>", addy.Address, addy.DisplayName);
            return answer;

        private static string MailAddressCollectionToString(MailAddressCollection mc)
            List<string> addies = new List<string>();
            foreach (MailAddress addy in mc)
            return string.Join(", ", addies.ToArray());

        /// <summary>
        /// Convert a MailMesage to a string
        /// </summary>
        /// <param name="msg">the MailMessage to convert</param>
        /// <returns>the MailMessage as a string</returns>
        public static string MessageToString(MailMessage msg)
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("FROM: {0}", MailAddresstoString(msg.From)).AppendLine();
            sb.AppendFormat("TO: {0}", MailAddressCollectionToString(msg.To)).AppendLine();
            sb.AppendFormat("CC: {0}", MailAddressCollectionToString(msg.CC)).AppendLine();
            sb.AppendFormat("BCC: {0}", MailAddressCollectionToString(msg.Bcc)).AppendLine();
            sb.AppendFormat("SUBJECT: {0}", msg.Subject).AppendLine();
            sb.AppendFormat("BODY: {0}", msg.Body).AppendLine();

            foreach (Attachment att in msg.Attachments)
                sb.AppendFormat("Attachment: {0}", att.Name);

            return sb.ToString();

 This class exposes a single static function MessageToString() that will convert a MailMessage object to a readable string.  Perfect for logging or sending in a notification email.

The output looks like this:
FROM: "Bryan" <>
TO: "Bob" <>, "Bill" <>, <>
CC: <>
SUBJECT: New WebSite Contact
BODY: Blah has submitted the following on the CONCACT.ASPX page.
   Name: Ruby


Bryan Valencia is a contributing editor and founder of Visual Studio Journey.  He owns and operates Software Services, a web design and hosting company in Manteca, California.

No comments:

Post a Comment

Contact Us


Email *

Message *