在Node.js中向SendGrid的“发件人”字段添加名称

41

我想使用SendGrid API在“发件人”字段中添加一个名称,但是我不知道该怎么做。 我尝试将sendgrid.send中的“from”参数设置为Name <example@example.com>,但是没有起作用。谢谢。

6个回答

125

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

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

谢谢你,我也遇到了同样的问题,而且在文档中找不到“name”字段,事实上,这些文档并不特别容易浏览。 - JMac
1
我同意。我已经提出了一个pull request,试图在文档中澄清这一点,但目前还没有成功。 - Incinerator
2
我在这里找到了文档:https://github.com/sendgrid/sendgrid-nodejs/blob/master/use-cases/flexible-address-fields.md - ptimson
3
这应该是针对 Sendgrid API V3 的被接受的答案。 - Trev14
1
这个可以运行。被接受的答案已经不能运行了。 - Or Assayag
显示剩余3条评论

18

1
优秀的回答! - hestellezg

17

您可以通过以下几种方式设置“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() { 
  // ... 
});

你可能想花几分钟时间浏览Github页面上的README文档。它对如何使用库以及提供的各种功能有相当详细的信息。


1
谢谢。我读了那个README,但不知为何在查找有关它的内容时,我没有在文档中看到“fromname”字段。下次我会尝试使用Ctrl+F :) - Ian Macalinao
什么是用户和密钥。我认为密钥是 API 密钥,但是用户是什么?那是用户名还是其他的东西? - suresh pareek
13
这不再起作用了。请查看下面@incinerator的答案。 - Pier
3
不再起作用了。看 https://dev59.com/LmQn5IYBdhLWcg3wiHnl#47903145 的答案。 - vohrahul
@Swift 这个不再起作用了。你能否在你的回答中提到这一点? - secretshardul
这是 GitHub 上的用例页面:https://github.com/sendgrid/sendgrid-nodejs/blob/main/docs/use-cases/README.md#email-use-cases - maxi-code

11

如果您正在使用nodejs助手库,请使用以下参数:

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

6

从GitHub上的节点库中,您可以使用以下任一方法来设置发送电子邮件和名称:

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

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

0

对于strapijs用户,在插件中您可以像下面这样进行更改

module.exports = ({ env }) => ({
  // ...
  email: {
    config: {
      provider: 'sendgrid',
      providerOptions: {
        apiKey: env('SENDGRID_API_KEY'),
      },
      settings: {
        defaultFrom: 'The Name You Want <myemail@protonmail.com>',
        defaultReplyTo: 'The Name You Want <myemail@protonmail.com>',
      },
    },
  },
  // ...
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接