1

I am using JavaScript to formulate a mailto: URI, but for some reason the \n characters are not working.

My string is constructed like this:

var emailBody = "This is the first line!\n" + "This is the next line.\n" + "And so on and so forth.\n";

And then I form a URL like:

var mailToLink = 'mailto:' + emailTo
               + '?subject=' + emailSubject
               + '&body=' + emailBody;

and instruct the browser to navigate to that URI:

var win = window.open(mailToLink, 'emailWindow');

My email client opens with the draft email in the window, but all the "lines" are displayed consecutively. I see no line breaks, except those rendered due to the email client's natural word wrapping.

How can I generate this email with the newline characters intact?

Lightness Races in Orbit
  • 369,052
  • 73
  • 620
  • 1,021
Chris
  • 966
  • 9
  • 29

1 Answers1

1

I create a variable: mailToLink = 'mailto:' + emailTo + ?subject=' + emailSubject + '&body=' + emailBody;

You can't have a literal new line in a URL.

You should pass each value through the encodeURIComponent() function when adding it to the URL string (which will take care of all characters with special meaning including new lines, +, % and so on).

Quentin
  • 857,932
  • 118
  • 1,152
  • 1,264
  • ABSOLUTE GENIUS! Worked like a charm! I am very pleased, because I don't see any answers like this anywhere else on Stack! Take your correct and upvote, good Sir. – Chris Sep 23 '15 at 19:12