Archive for the ‘Networking’ Category

Content-Transfer-Encoding System.Net.Mail.MailMessage

March 4, 2009

If you have tried to send an email using the System.Net.Mail.MailMessage class and System.Net.Mail.SmtpClient class, you may have come across the problem described in this blog post.  The recipient may receive a garbled message, in which carriage returns are not recognized and are shown are strange characters instead:

This is a test message.=0D=0ANew line should start here.=0D=0A

However, when opening the mail in Outlook, it may appear fine.  It took me some time to figure out what was happing.  I used the TcpTrace tool for intercepting the actual message being sent.  The message message had the following items in its header:

Content-Transfer-Encoding: quoted-printable

When using the obsolete System.Web.Mail classes, the Content-Transfer-Encoding had been 7bit instead of quoted-printable.  I thought the strange characters might have something to do with the Content-Transfer-Encoding being used, and started playing around with the AlternativeView class to add an alternative view to my message which, hopefully, would display correctly in the recipient’s client.  Unfortunately, adding an AlternativeView leaves the original view in the message as well, and this particular client still tried to read that original view. 

At first, I thought I would have to revert to the old System.Web.Mail client.  I decided to try one more Google search to see if there was a way around this, and found a comment by Stanley Roark, buried on the MSDN Library’s page about the MailMessage class.  This solution worked so well for me that I decided it deserved a blog post in its own right, hoping it would make it easier for people to find this solution.  My version of the code, in which you will have to replace some of the strings with those appropriate for your own message:

MailMessage message = new MailMessage(
    "from@somepany.com", "to@somepany.com");
message.Subject = "Some Subject";
message.IsBodyHtml = false;
message.Body = null;
using (AlternateView body =
    AlternateView.CreateAlternateViewFromString(
        "Some Message Body",
        message.BodyEncoding,
        message.IsBodyHtml ? "text/html" : null))
{
    body.TransferEncoding = 
        TransferEncoding.SevenBit;
    message.AlternateViews.Add(body);
    try
    {
        SmtpClient smtp = new SmtpClient("mail.somepany.com", 25);
        smtp.Send(message);
    }
    catch (SmtpException ex)
    {
        System.Diagnostics.Debug.WriteLine(
            ex.Message);
    }
} 

If you found this post helpful, please click below to “Kick” it:

kick it on DotNetKicks.com