Domanda

I have an ASP.NET web application that has a page that sends emails to a list of recipients. This page has an asp:TextBox where the body of the mail is typed in:

<asp:TextBox ID="txtBody" runat="server" Height="151px" TextMode="MultiLine" Width="550px" Visible="False" MaxLength="160"></asp:TextBox>

The page then makes use of a REST service to insert the email details into a database:

EmailBatchHelper.SendBatch(recipients, txtNotificationTo.Text, txtFrom.Text.TrimEnd(), txtBody.Text, txtSubject.Text, strAtt);

A windows service reads the emails from the database and sends them using smpt.

The problem that I'm having is the line-breaks in the body are removed somewhere along the line. I'm guessing when it gets inserted into the database. How can I have any line-breaks still be present in the message received by the user?

Update: I debugged the windows service and determined that the following:

inserted into the database is the word test twice with 2 linebreaks in between. The value set to the Body of the MailMessage is the following:

mail.Body = "test\r\n\r\ntest";

Now I'm thinking there might be a setting on MailMessage to interpret linebreaks in the Body

È stato utile?

Soluzione

As shown in the comments above, the most common reason for this behavior is trying to send plain text as an HTML-encoded message. The carriage return/newline characters have no meaning in HTML, so the line breaks do not show up. So, there are two quick fixes:

  • Make sure the IsBodyHtml property is set to false on your MailMessage object(s), or
  • Replace any instances of \r\n with <br /> elements, then set IsBodyHtml to true. This can be done with one simple line:

    _yourEmailContent.Replace(Environment.NewLine, "<br />").ToString();

Another alternative is to encode/convert the newline/return characters as entities:

_yourEmailContent.Replace(Environment.NewLine, "&#x000D;&#x000A;").ToString();

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top