首页 > 解决方案 > StringContext$InvalidEscapeException: 在创建 HTML 字符串主体时,无效转义 '\:' 不是 [\b、\t、\n、\f、\r、\\、\"、\'] 之一

问题描述

在用户注册时,我想向用户发送一封带有html正文的电子邮件。我创建的电子邮件模板如下:

object EmailHTML {
  val body =
    s"""
<html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns:m="http://schemas.microsoft.com/office/2004/12/omml" xmlns="http://www.w3.org/TR/REC-html40"><head>
<meta http-equiv="Content-Type" content="text/html; charset=Windows-1252">
<meta name="Generator" content="Microsoft Word 15 (filtered medium)">
<!--[if !mso]><style>v\:* {behavior:url(#default#VML);}
o\:* {behavior:url(#default#VML);}
w\:* {behavior:url(#default#VML);}
.shape {behavior:url(#default#VML);}
</style><![endif]-->
...
""".stripMargin
}

我像这样使用它:

val html = if(userToken.tokenType == UserTokenType.RegistrationConfirmation){
        EmailHTML.body 
      }else {
        EmailHTML.body 
      }
SignupEmail(subject,from,html)

当我执行代码时,我收到以下错误:

Caused by: scala.StringContext$InvalidEscapeException: invalid escape '\:' not one of [\b, \t, \n, \f, \r, \\, \", \'] at index 454 in "
       |<html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns:m="http://schemas.microsoft.com/office/2004/12/omml" xmlns="http://www.w3.org/TR/REC-html40"><head>
    ...

如果我删除该行,则不会发生异常:

<!--[if !mso]><style>v\:* {behavior:url(#default#VML);}
o\:* {behavior:url(#default#VML);}
w\:* {behavior:url(#default#VML);}
.shape {behavior:url(#default#VML);}
</style><![endif]-->

但是我收到的电子邮件格式不正确!可能是什么问题,这条线的重要性是什么?

<!--[if !mso]><style>v\:* {behavior:url(#default#VML);}
o\:* {behavior:url(#default#VML);}
w\:* {behavior:url(#default#VML);}
.shape {behavior:url(#default#VML);}
</style><![endif]-->

标签: stringscala

解决方案


您可能会发现有用的另一个解决方案是删除sbefore """

val body1 = """
<html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns:m="http://schemas.microsoft.com/office/2004/12/omml" xmlns="http://www.w3.org/TR/REC-html40"><head>
<meta http-equiv="Content-Type" content="text/html; charset=Windows-1252">
<meta name="Generator" content="Microsoft Word 15 (filtered medium)">
<!--[if !mso]><style>v\:* {behavior:url(#default#VML);}
o\:* {behavior:url(#default#VML);}
w\:* {behavior:url(#default#VML);}
.shape {behavior:url(#default#VML);}
</style><![endif]-->
...""".stripMargin

这将导致字符串不被评估,因此它将保持原样。

在Scastie运行的代码。


推荐阅读