Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
524 views
in Technique[技术] by (71.8m points)

html - Javascript adding linebreak in mailto body

I'm setting the body of an email using values from a form

  firstname = bob
  lastname = dole

   ebody = 'First Name: ' + firstname + '
' + 'Last Name: ' + lastname

  window.location.href = 'mailto:[email protected]?subject=test
  email&body=' + ebody;

If I do an "alert(ebody);" I get the linebreak between firstname & lastname, however when it opens up outlook, the entire ebody string appears without a linebreak in the email body.

I've tried just also. is there something that can give be a line break?

Thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

RFC 2368 says that mailto body content must be URL-encoded, using the %-escaped form for characters that would normally be encoded in a URL. Those characters includes spaces and (as called out explicitly in section 5 of 2368) CR and LF.

You could do this by writing

ebody = 'First%20Name:%20' + firstname + '%0D%0A' + 'Last%20Name:%20' + lastname;

but it's easier and better to have JavaScript do the escaping for you, like this:

ebody = 'First Name: ' + firstname + '
' + 'Last Name: ' + lastname;
ebody = encodeURIComponent(ebody);

Not only will that save you from having to identify and look up the hex values of characters that need to be encoded in your fixed text, it will also encode any goofy characters in the firstname and lastname variables.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...