You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取邮件发件人显示名称?附测试代码

如何获取Gmail邮件发件人的显示名称?

当然可以获取发件人的显示名称,但要注意这个字段是可选的,部分邮件可能没有设置,这种情况下只能拿到邮箱地址。

你当前代码里用msg.getHeader("Display-Name")是错误的,邮件头里不存在这个字段,发件人信息统一放在From头中,格式通常为显示名称 <邮箱地址>,也可能直接是纯邮箱地址。

正确实现方法

先写一个辅助函数来解析From头,提取显示名称:

function getSenderDisplayName(message) {
  var fromHeader = message.getHeader("From");
  if (!fromHeader) return null;
  
  // 匹配带引号或不带引号的显示名称
  var displayNameMatch = fromHeader.match(/^"?([^"<]+)"?\s*</);
  if (displayNameMatch) {
    return displayNameMatch[1].trim();
  } else {
    // 没有显示名称时,返回邮箱地址(也可改为返回null)
    return fromHeader.trim();
  }
}

然后修改你的测试函数,用上这个辅助函数:

function myTestFunction() {
  var threads = GmailApp.search("in:spam");
  for (var i = 0; i < threads.length; i++) {
    var msg = threads[i].getMessages()[0];
    console.log(i);
    
    var displayName = getSenderDisplayName(msg);
    // 处理显示名称不存在的情况,再做匹配检查
    if (displayName && displayName.match(/(John Doe)|(Jane Doe)/gi)) {
      console.log('Found it!');
      continue;
    }
  }
}

补充说明

  • From头的常见格式有三种:John Doe <john.doe@abc123.org>、"John Doe" <john.doe@abc123.org>、纯邮箱地址john.doe@abc123.org,上面的正则可以覆盖这些场景。
  • 如果遇到非英文的显示名称(比如含中文、特殊字符),可能存在编码问题,这时可以用Utilities.parseString来处理编码解析。
  • 若不需要在无显示名称时返回邮箱地址,可将辅助函数的else分支改为return null。

内容的提问来源于stack exchange,提问作者crjunk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 03:42:46