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
  • 378,754
  • 76
  • 643
  • 1,055
Chris
  • 1,091
  • 11
  • 32

1 Answers1

2

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

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

You should generate your query strings using URLSearchParams instead of mashing strings together. That will take care of any escaping that needs to be done.

const emailTo = "example@example.com";
const emailSubject = "Visit a café";
const emailBody = `This is a body which includes
a new line!`;

const url = new URL(`mailto:${emailTo}`);
url.searchParams.set('subject', emailSubject);
url.searchParams.set('body', emailBody);

var mailToLink = url.toString();
console.log(mailToLink);

2015 answer:

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
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 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