【问题标题】:Adding a name to the "from" field in SendGrid in Node.js在 Node.js 的 SendGrid 中向“发件人”字段添加名称
【发布时间】:2025-12-27 23:05:06
【问题描述】:

我想使用 SendGrid API 为我的“发件人”字段添加一个名称,但我不知道如何执行此操作。我尝试将sendgrid.send 中的“from”参数设置为Name <example@example.com>,但这不起作用。谢谢。

【问题讨论】:

    标签: node.js sendgrid


    【解决方案1】:

    使用最新版本的Sendgrid Node.js library 中使用的语法更新了示例。

    sendgrid.send({
      to: 'you@yourdomain.com',
      from: {
          email: 'example@example.com',
          name: 'Sender Name'
      },
      subject: 'Hello World',
      text: 'My first email through SendGrid'
    });
    

    【讨论】:

    • 谢谢你,同样的问题,我在文档中找不到 name 字段,实际上文档并不是特别容易浏览。
    • 我同意。我已经发布了pull request 试图在文档中澄清这一点,但到目前为止无济于事。
    • 不知道几个月前是不是这样,但现在github有记录
    • 这应该是 Sendgrid API V3 的公认答案
    【解决方案2】:

    您可以通过以下几种方式设置 from 参数:

    var SendGrid = require('sendgrid').SendGrid;
    var sendgrid = new SendGrid(user, key);
    sendgrid.send({
      to: 'you@yourdomain.com',
      from: 'example@example.com',  // Note that we set the `from` parameter here
      fromname: 'Name', // We set the `fromname` parameter here
      subject: 'Hello World',
      text: 'My first email through SendGrid'
    }, function(success, message) {
      if (!success) {
        console.log(message);
      }
    });
    

    或者您可以创建一个Email 对象并在上面填写内容:

    var Email = require('sendgrid').Email;
    var email = new Email({
      to: 'you@yourdomain.com',
      from: 'example@example.com',
      fromname: 'Name',
      subject: 'What was Wenger thinking sending Walcott on that early?',
      text: 'Did you see that ludicrous display last night?'
    });
    
    sendgrid.send(email, function() { 
      // ... 
    });
    

    您可能需要花几分钟时间查看the README document on the Github page。它包含有关如何使用该库及其提供的各种功能的非常详细的信息。

    【讨论】:

    • 谢谢。我阅读了该自述文件,由于某种原因,我在尝试查找有关它的内容时没有在文档中看到 fromname 字段。下次我会尝试 Ctrl+F :)
    • 什么是用户和密钥。我在想那是关键是 api 关键但什么是用户?那是用户名或任何其他
    • 这不再起作用了。请参阅下面的@incinerator 答案。
    • 这不再起作用了。看*.com/a/47903145/2803872答案。
    • @Swift 这不再起作用了。您能否在回答中提及这一点?
    【解决方案3】:

    虽然更新的用例不包括from

    https://github.com/sendgrid/sendgrid-nodejs/blob/master/docs/use-cases/flexible-address-fields.md

    这个对我有用

      to: 'user@userdomain.com',
      from: {
          name: 'Sender'
          email: 'me@mydomain.com',
      },
      subject: 'Hello World',
      html: `<html><p>Hello World</p></html>`
    });
    

    【讨论】:

    • 优秀的答案!
    【解决方案4】:

    如果您使用的是 nodejs Helper 库,请使用以下参数:

    from_email = new helper.Email("email@domain.com", "Email Name");
    

    【讨论】:

      【解决方案5】:

      从节点库上的 github,您可以使用以下任一方法从电子邮件和名称发送

      from: {
         name: 'Name Here',
         email: 'email here'
      }
      

      from: "Cool Name <some@email.com>"
      

      【讨论】: