locked
Emails sent incorrectly formatted with =0D=0A instead of line breaks

    Question

  • Hey everyone,

     I have a problem sending email to our users (email is being sent through SendMail on a Solaris box)

     

    The .Net Version 1.1 methods works correctly however using the .Net version 2.0 causes funny characters (line break)

    Here is an example of the email being sent

     

     

    ----boundary_0_447da158-165f-4e4f-b60a-c9f64960b326
    content-type: multipart/alternative; boundary=--boundary_1_d760c034-668f-4ed2-a7ee-465a2b4c6db2


    ----boundary_1_d760c034-668f-4ed2-a7ee-465a2b4c6db2

    content-type: text/plain; charset=us-ascii
    content-transfer-encoding: quoted-printable

    =0D=0A =0D=0A Dear chris mckelt,=0D=0A =0D=0A Your request=
    for a password reset has been received and processed.=0D=0A =0D=0A=
    Your new password is Urn78714.=0D=0A =
    =0D=0A For further help, or if you are unsure why you have received=
    this mail, =0D=0A please contact Customer Services: http://OurUrl.com/contacts/support.htm=
    =0D=0A =0D=0A Please do not reply to this e-mail address.=0D=0A=
    =0D=0A
    ----boundary_1_d760c034-668f-4ed2-a7ee-465a2b4c6db2
    content-type: text/plain; charset=us-ascii
    content-transfer-encoding: sevenbit
     
    Here is the code
     
     
      public override void SendEmail(UserCredentials credentials, string toAddress, string fromAddress, string subject, string body)
    {
    using (Impersonation impersonation = new Impersonation(credentials))
    {
    using (MailMessage mailMessage = new MailMessage())
    {
    mailMessage.From = new MailAddress(fromAddress);
    mailMessage.To.Add(new MailAddress(toAddress));
    mailMessage.Sender = new MailAddress(fromAddress);
    mailMessage.Subject = subject;
    mailMessage.Body = body;
    mailMessage.IsBodyHtml = false;

    AlternateView plainView = AlternateView.CreateAlternateViewFromString(body, Encoding.ASCII, "text/plain");
    plainView.TransferEncoding = System.Net.Mime.TransferEncoding.SevenBit;
    mailMessage.AlternateViews.Add(plainView);

    bool success = false;
    string innerException = "Failed to send email to " + toAddress;

    string smtpServerAddresses = ConfigurationManager.AppSettings["SMTPServers"];

    foreach (string address in smtpServerAddresses.Split(Convert.ToChar(",")))
    {

    string trimedAddress = string.Empty;

    try
    {
    if (!success)
    {
    if (!string.IsNullOrEmpty(address))
    {
    trimedAddress = address.Trim();
    }

    SmtpClient smtpServer = new SmtpClient(trimedAddress);
    smtpServer.Send(mailMessage);
    success = true;
    }
    }
    catch (Exception ex)
    {
    try
    {
    innerException = ex.InnerException.Message;
    }
    catch { }

    EventLogger.WriteToEventLog("Error sending email using SMTP server " + address, ex, System.Diagnostics.EventLogEntryType.Warning);
    }
    }

    if (!success)
    {
    throw new ApplicationException(innerException);
    }
    }
    }
    }
      
     Anyone have any ideas?  Thanks in advance :)
    Wednesday, September 27, 2006 8:01 PM

All replies

  • If anyone can help spread so light on this I would also be interested since I am having a similar issue. As above I am creating a MailMessage and sending it using an SMTPClient in .NET 2 although this time it is sent via an Exchange 2003 server.

    Viewing my mails with Outlook Express results in the \r\n formatting as sent.

    However, the Exchange server is used by another program to forward the mail on but using a completely different protocol and transmission method, effectively only using mail box on the Exchange server as a buffer to store outbound messages. When this code access the messages in exchange sever mail box I find all \r\n's have been replaced by the ASCII codes =0D=0A. This replacement would appear to be happening after the mail is sent using the SMTPClient since I can see that the formatting is correct up until this point.

    The strange thing is, if I create a mail using Outlook Express and send it to the exchange server, when I view it in the Outbound message program the formatting is correct using \r\n for a new line. Also any messgae I send using the SMTPClient which is then forwarded by outlook express to the exchange inbox and then viewed by the outbound message program regains the correct \r\n formatting.

    I can't seem to see where the =0D=0A is being introduced or how to stop it occuring. I know the email message protocal allows for this replacement to occur, but somehow using Outlook Express this does not happen so I guess it must be optional.

    I do not have the option of changing the code of the outbopund message program which has been provided to me so I need to stop the replacement in the first place rather than re substuturte the \r\n.

    Can anyone help please?

     

     

    Wednesday, October 04, 2006 1:25 PM
  • After testing both Send methods on the .NET SMTP client to remove the MailMessage from the equiation and due to a lack of response to this post I decided it would be a good test to knock up my own SMTP client.

    The code below is a class which will attach to an SMTP server over a tcpip socket and send the mail. All original formatting is preserved so the =0D=0A replacement must occur in the .NET 2.0 SMTPClient class and I have yet to find a way of removing it.

    The class very barebones and doesn't return any info on failure (apart from a true false flag), but can be easily augmented.
    Feel free to use it.

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

    namespace MailClient
    {
        class SMTPClientSocket
        {
            string mSMTPServer;
            Socket mSMTPSocket;
            int mSMTPPort;

            public SMTPClientSocket(string smtpServer, int smtpPort)
            {
                mSMTPServer = smtpServer;
                mSMTPPort = smtpPort;
            }

            private bool Connect()
            {
                bool success = false;

                try
                {
                    if (mSMTPSocket == null)
                    {
                        mSMTPSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                        mSMTPSocket.ReceiveBufferSize = 8192;
                    }

                    mSMTPSocket.Connect(mSMTPServer, mSMTPPort);

                    if (Recieve().StartsWith("220"))
                    {
                        success = true;
                    }
                }

                catch (Exception exception)
                {
                }
                return success;
            }

            private void Disconnect()
            {
                if (mSMTPSocket != null)
                {
                    if (mSMTPSocket.Connected)
                    {
                        mSMTPSocket.Shutdown(SocketShutdown.Both);
                        mSMTPSocket.Close(0);
                        mSMTPSocket = null;
                    }
                }
            }

            public bool SendMail(string message, string subject, string to, string from, string alias)
            {

                bool success = false;

                if (Connect())
                {
                    if (Handshake())
                    {
                        if (MailFrom(from))
                        {
                            if (MailTo(to))
                            {
                                if (SendMessage(message, subject, alias))
                                {
                                    if (Finish())
                                    {
                                        Disconnect();
                                        success = true;
                                    }
                                }
                            }
                        }
                    }
                }
                return success;
            }

            private bool Handshake()
            {
                bool success = false;

                if (Send("HELO\r\n"))
                {
                    if (Recieve().StartsWith("250"))
                    {
                        success = true;
                    }
                }

                return success;
            }

            private bool MailFrom(string from)
            {
                bool success = false;

                if (Send("MAIL FROM:<" + from + ">\r\n"))
                {
                    if (Recieve().StartsWith("250"))
                    {
                        success = true;
                    }
                }

                return success;
            }

            private bool MailTo(string to)
            {
                bool success = false;

                if (Send("RCPT TO:<" + to + ">\r\n"))
                {
                    if (Recieve().StartsWith("250"))
                    {
                        success = true;
                    }
                }

                return success;
            }

            private bool SendMessage(string message, string subject, string alias)
            {
                bool success = false;

                if (Send("DATA\r\n"))
                {
                    if (Recieve().StartsWith("354"))
                    {
                        string all = "Subject: " + subject + "\r\nFrom: " + alias + "\r\n\r\n" + message + "\r\n.\r\n";

                        if (Send(all))
                        {
                            if (Recieve().StartsWith("250"))
                            {
                                success = true;
                            }
                        }
                    }
                }
                return success;
            }

            private bool Finish()
            {
                return Send("Quit\r\n");
            }

            private bool Send(string data)
            {
                bool success = false;

                try
                {

                    byte[] bytes = System.Text.Encoding.ASCII.GetBytes(data.ToCharArray());
                    mSMTPSocket.Send(bytes);
                    success = true;
                }
                catch (Exception exception)
                {
                }
                return success;
            }

            private string Recieve()
            {
                string data = "";

                try
                {

                    byte[] bytes = new byte[mSMTPSocket.ReceiveBufferSize];
                    mSMTPSocket.Receive(bytes);
                    data = System.Text.Encoding.ASCII.GetString(bytes);
                }
                catch (Exception exception)
                {
                }

                return data;
            }

        }
    }

    Thursday, October 05, 2006 9:30 AM
  • I have not yet figured out how to resolve the .net 2.0 Net.Mail issue.  But you can still use the Web.Mail class.

    Problem with using System.Net.Mail in .net 2.0

    In some email clients, the sent message body will contain the sequence =0D=0A where you would be expecting a linebreak.

    The problem is related to content-transfer-encoding - by default in .net 2.0 it's quoted-printable, in old .net it was 8bit.

    Setting the header like this emailMessage.Headers.Set("content-transfer-encoding", "8bit") will not work because .NET will add one more time content-transfer-encoding, and it will add the default one.  Anyone know how to stop it from doing this?

    So you need to simply use the old obsolete class: System.Web.Mail.MailMessage

    - Jim

    Monday, March 19, 2007 5:06 PM
  • Hi~ Chris McKelt!

     

    This is Bong-Sub from South Korea.

    I saw your article on Microsoft forums Website.

    Have you found the solution on fixing the content-transfer-encoding to quoted-printable in the mail header.

     

    I'm facing with that problem right now.

    If you know the alternative solution about that, could you tell me? please!

     

    Have a nice day~!

    Wednesday, July 18, 2007 5:28 AM
  • I now have this problem, is there a solution for >= .net 2.0 Net.Mail??
    Thursday, December 06, 2007 1:28 PM
  • I now have this problem, is there a solution for >= .net 2.0 Net.Mail??

    i'm using .Net 1.1 and i deal with the same issue when i forward the email i got %0d%0a does somone could help me to stoppiing that ?
    Sunday, March 29, 2009 9:32 PM