【问题标题】:Replace Emails and HREFS with enclosing HREFS用封闭的 HREFS 替换电子邮件和 HREFS
【发布时间】:2011-02-24 01:09:49
【问题描述】:

我有一个以前是纯文本的电子邮件正文,但现在我将其设为 HTML。电子邮件是使用多种方法生成的,但都不容易转换。

我拥有的是:

Some content emailaddress@something.com, some http://www.somewebsite/someurl.aspx.

我想做的是创建一个函数,自动将所有电子邮件地址和所有 URL 包含在 HREF 标记中的 string 中,以便 HTML 电子邮件在所有电子邮件客户端中正确读取。

有人有这个功能吗?

【问题讨论】:

    标签: c# email html-email


    【解决方案1】:

    您说您想将所有电子邮件和 URL 包含在一个字符串中 - 您的意思是引用?如果是这样,那么这样的事情就可以解决问题。它识别电子邮件和网址。因为我们假设该字符串设置了电子邮件地址/url 的长度,所以正则表达式故意宽松 - 在这里试图过于具体可能意味着某些合法案例不匹配。

    public string LinkQuotedEmailsAndURLs(string email)
    {
        Regex toMatch = new Regex("((https?|ftp)?://([\\w+?\\.\\w+])+[^ \"]*)|\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*", RegexOptions.IgnoreCase);
    
        MatchCollection mactches = toMatch.Matches(email);
    
        foreach (Match match in mactches) {
            email = email.Replace(match.Value, "<a href=" + match.Value + ">" + match.Value.Substring(1,match.Value.Length-2) + "</a>");
        }
    
        return email;
    }
    

    不清楚原始文本是否包含实际的 url 编码 URL 或“可呈现”的 url 解码形式。您可能希望在匹配值上使用 HttpUtils.UrlEncode/UrlDecode 以确保嵌入的 href 被编码,而呈现的字符串被解码,因此 href 包括“%20”,但这些在链接文本中显示为常规字符。

    例如如果已经存在的文本是实际的 URL,那么您可以使用

        email = email.Replace(match.Value, "<a href=" + match.Value + ">" + 
           HttpUtils.UrlEncode(match.Value.Substring(1,match.Value.Length-2)) + "</a>");
    

    【讨论】:

      【解决方案2】:

      这里我们需要一些正则表达式的魔法。首先我们找到电子邮件。我希望我们不需要验证它们,所以任何没有空格的单词都带有 @ 后跟 .没问题。

      public static string MakeEmailsClickable( string input ){
        if (string.IsNullOrEmpty(input) ) return input;
        Regex emailFinder = new Regex(@"[^\s]+@[^\s\.]+.[^\s]+", RegexOptions.IgnoreCase);
        return emailFinder.Replace(input, "<a href=\"mailto:$&\">$&</a>" );
      }
      

      $&amp; - 表示正则表达式中的当前匹配项。

      要查找 Url,我们假设它们以某个协议名称开头,后跟 ://,同样,其中不允许有空格。

      public static string MakeUrlsClickable( string input ){
        if (string.IsNullOrEmpty(input) ) return input;
        Regex urlFinder = new Regex(@"(ftp|http(s)?)://[^\s]*", RegexOptions.IgnoreCase);
        return urlFinder.Replace(input, "<a href=\"$&\">$&</a>" );
      }
      

      这会查找 ftp、http 或 https 链接,但您可以将任何协议添加到正则表达式中,并使用 |(管道)将其分隔,如下所示:(file|telnet|ftp|http(s)?)://[^\s]*)

      其实URL中也可能有@http://username:password@host:port/,但我希望不是这样,因为那样我们将不得不使用一些更严格的正则表达式。

      【讨论】:

        【解决方案3】:

        我会使用正则表达式来查找它们。看看这个博客,Regex to find URL within text and make them as link 一个很好的起点。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-11-28
          • 2020-08-03
          • 1970-01-01
          • 1970-01-01
          • 2013-07-01
          • 2011-05-01
          • 2021-10-15
          • 1970-01-01
          相关资源
          最近更新 更多