Search code examples
htmlemailurimailto

\n is removed from my email body


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?


Solution

  • 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).