【问题标题】:How can I properly parse an email address with name?如何正确解析带有名称的电子邮件地址?
【发布时间】:2012-03-17 13:36:41
【问题描述】:

我正在阅读电子邮件标头(在 Node.js 中,用于记分的人),它们各不相同。 to 字段中的电子邮件地址如下所示:

"Jake Smart" <jake@smart.com>, jack@smart.com, "Development, Business" <bizdev@smart.com>

以及其他多种格式。有什么办法可以解析出所有这些吗?

这是我的第一个刺:

  1. - 上运行split() 将不同的人分成一个数组
  2. 对于每个项目,查看是否有 &lt;"
  3. 如果有&lt;,则解析出电子邮件
  4. 如果有",则解析出名称
  5. 对于名称,如果有 ,,则拆分以获取姓氏、名字。

如果我首先对, 进行拆分,那么Development, Business 将导致拆分错误。空格也不一致。另外,我以前从未见过的标题中可能包含更多的电子邮件地址格式。有没有什么方法(或者可能是一个很棒的 Node.js 库)可以为我完成所有这些工作?

【问题讨论】:

    标签: parsing node.js email-headers


    【解决方案1】:

    我会尝试在一次迭代中完成所有操作(性能)。把它放在一起(有限测试):

    var header = "\"Jake Smart\" <jake@smart.com>, jack@smart.com, \"Development, Business\" <bizdev@smart.com>";
    alert (header);
    var info = [];
    var current = [];
    var state = -1;
    var temp = "";
    for (var i = 0; i < header.length + 1; i++) {
      var c = header[i];
      if (state == 0) {
        if (c == "\"") {
          current.push(temp);
          temp = "";
          state = -1;
        } else {
          temp += c;
        }
      } else if (state == 1) {
        if (c == ">") {
          current.push(temp);
          info.push (current);
          current = [];
          temp = "";
          state = -1;
        } else {
          temp += c;
        }
      } else {
        if (c == "<"){
          state = 1;
        } else if (c == "\"") {
          state = 0;
        }
      }
    }
    
    alert ("INFO: \n" + info);
    

    【讨论】:

      【解决方案2】:

      它的实际格式非常复杂,但这里有一个有效的正则表达式。我不能保证它总是会起作用。 https://www.rfc-editor.org/rfc/rfc2822#page-15

      const str = "...";
      const pat = /(?:"([^"]+)")? ?<?(.*?@[^>,]+)>?,? ?/g;
      
      let m;
      while (m = pat.exec(str)) {
        const name = m[1];
        const mail = m[2];
      
        // Do whatever you need.
      }
      

      【讨论】:

      • 请将“m”声明为局部变量
      【解决方案3】:

      为了完整的东西,你应该把它移植到 JS:http://cpansearch.perl.org/src/RJBS/Email-Address-1.895/lib/Email/Address.pm

      它为您提供所需的所有部件。棘手的一点是一开始的一组正则表达式。

      【讨论】:

        【解决方案4】:

        为此有一个 npm 模块 - mimelib(或 mimelib-noiconv,如果您在 Windows 上或不想编译 node-iconv)

        npm install mimelib-noiconv
        

        而用法是:

        var mimelib = require("mimelib-noiconv");
        var addressStr = 'jack@smart.com, "Development, Business" <bizdev@smart.com>';
        var addresses = mimelib.parseAddresses(addressStr);
        
        console.log(addresses);
        // [{ address: 'jack@smart.com', name: '' },
        //  { address: 'bizdev@smart.com', name: 'Development, Business' }]
        

        【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-01-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-27
        • 2014-07-18
        相关资源
        最近更新 更多