Andy
Andy

Reputation: 1709

textbox text as html for an email in c#

I am trying to send an smtp email from my c# web site. it sends fine all except when a textbox text has line breaks in it it does not format these in the email.. instead it just has one long string of text.

the email is html encoded so how do i make this:

tbDeliver.Text

keep the line breaks in the email?

Thanks in advance

Upvotes: 2

Views: 6865

Answers (7)

dave wanta
dave wanta

Reputation: 7214

ACK!

NEVER EVER EVER use Environment.NewLine to replace <BR> tags in email.

I can't stress this enough.

On some platforms, Environment.NewLine will be \n's, which is a huge no-no in the SMTP world.

In SMTP, all line breaks must be \r\n.

Eventually, your mail will get rejected as spam by some servers using only \n.

always use \r\n or vbCrLf to replace <br> tags.

Upvotes: -1

Ray
Ray

Reputation: 21905

I do this with a regular expression to make sure I get any flavor of newline:

Regex matchNewLine = new Regex("\r\n|\r|\n", RegexOptions.Compiled | RegexOptions.Singleline);
string result = matchNewLine.Replace(originalText, "<br />");

Upvotes: 4

Ali Tarhini
Ali Tarhini

Reputation: 5358

make sure that the body format of the message is of type Html. if you are using system.web to send mail :

System.Web.Mail.MailMessage mail = new System.Web.Mail.MailMessage();
mail.BodyFormat = Web.Mail.MailFormat.Html;

if you are using system.net :

    System.Net.Mail.MailMessage mail = New System.Net.Mail.MailMessage();
    mail.IsBodyHtml = True;

Upvotes: 2

Klaus Byskov Pedersen
Klaus Byskov Pedersen

Reputation: 120917

Html encode the linebreaks to '<br/>' or '<p>' tags.

Upvotes: 0

Sani Huttunen
Sani Huttunen

Reputation: 24375

Try this:

var textBoxText = tbDeliver.Text.Replace(Environment.NewLine, "<br>");

Upvotes: 8

jball
jball

Reputation: 25014

You'll need to replace \n with <br> in tbDeliver.Text.

string formatted = tbDeliver.Text.Replace ("\n", "<br />");

Upvotes: 0

Lloyd
Lloyd

Reputation: 29668

You could replace \r\n in .Text with <br/> that might work, do you output in a paragraph <p>?

Upvotes: 0

Related Questions