Javascript Javascript在mailto正文中添加换行符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10219781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript adding linebreak in mailto body
提问by srini
I'm setting the body of an email using values from a form
我正在使用表单中的值设置电子邮件的正文
firstname = bob
lastname = dole
ebody = 'First Name: ' + firstname + '\r\n' + '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.
如果我做一个“警报(ebody);” 我得到了名字和姓氏之间的换行符,但是当它打开 Outlook 时,整个 ebody 字符串出现在电子邮件正文中没有换行符。
I've tried just \n also. is there something that can give be a line break?
我也试过 \n 。有什么东西可以换行吗?
Thanks in advance
提前致谢
回答by ottomeister
RFC 2368says 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.
RFC 2368规定 mailto 正文内容必须是 URL 编码的,对通常在 URL 中编码的字符使用 % 转义形式。这些字符包括空格和(在 2368 的第 5 节中明确指出)CR 和 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:
但是让 JavaScript 为你做转义更容易也更好,就像这样:
ebody = 'First Name: ' + firstname + '\r\n' + '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.
这不仅可以让您不必识别和查找需要在固定文本中编码的字符的十六进制值,它还可以对firstname
和lastname
变量中的任何愚蠢的字符进行编码。
回答by AKZap
You can just use the Encoding %0D%0A
for line breaks.
您可以只使用编码 %0D%0A
换行。
firstname = 'Aung ';
lastname = 'Kyaw Zaw';
ebody = 'First Name: ' + firstname + '%0D%0A' + 'Last Name: ' + lastname;
window.location.href = 'mailto:[email protected]?subject=testemail&body=' + ebody;
回答by Adam Seabridge
I would expect outlook to try and output this as html/rich text so in that case you would need something like the following (including a urlencoded br tag):
我希望 Outlook 尝试将其输出为 html/富文本,因此在这种情况下,您需要类似以下内容(包括 urlencoded br 标签):
firstname = bob
lastname = dole
ebody = 'First Name: ' + firstname + '%3C%2Fbr%3E' + 'Last Name: ' + lastname
window.location.href = 'mailto:[email protected]?subject=test
email&body=' + ebody;