【问题标题】:While importing sendgrid mail it is not working导入 sendgrid 邮件时它不起作用
【发布时间】:2025-12-03 06:05:01
【问题描述】:

我想使用@sendgrid/mail 发送邮件,但是当我导入它时它不起作用。我的代码 sn-p 如下,

import * as sgMail from '@sendgrid/mail';

function sendMail(msg) {
  sgMail.setApiKey("API-KEY");
  sgMail.send(msg, (err, result) => {
    if(err){
        console.error(err);
    }

    console.log(result);
  });
}

const obj = {
    to: "mail@gmail.com",
    from: "no-reply@gmail.com",
    subject: "abc",
    text: "abc",
    html: "<h1>Working</h1>",
}
sendMail(obj);

这是我做的代码,所以现在问题是 sgMail.setApiKey is not a function error pops.

如果我删除 setApiKet 则 sgMail.send is not a function error pops.

所以,如果您有任何解决方案,请告诉我。

【问题讨论】:

  • 你做过这个 npm install --save @sendgrid/mail
  • 是的,我已经这样做了
  • 包为commonjs格式。使用const sgMail = require('@sendgrid/mail') 或尝试默认导出import sgMail from '@sendgrid/mail'
  • sendMail(obj);更改为 sendMail(obj, sgMail);和函数 sendMail(msg, sgMail)

标签: javascript node.js sendgrid


【解决方案1】:

如果您查看您尝试导入的 source,您会发现它导出了 MailService 的默认实例和类本身的命名导出。当您通过以下方式导入时:

import * as sgMail from '@sendgrid/mail';

该文件的所有导出都导出为新对象 (sgMail)。有几种方法可以保持这种语法,并且仍然可以做你想做的事:

// use the default instance which is exported as 'default'
sgMail.default.send(obj); 
// explictly create your own instance
const svc = new sgMail.MailService();
svc.send(obj);

不过,还有一个更简单的方法,就是直接导入default实例

import sgMail from '@sendgrid/mail'

【讨论】:

  • import sgMail from '@sendgrid/mail';之后,然后是以下任一工作:sgMail.setApiKey(process.env.SENDGRID_API_KEY);new sgMail.MailService().setApiKey(process.env.SENDGRID_API_KEY);
【解决方案2】:

你可以试试这个来自npmjs网站的代码参考npmjs sendgrid/mail

const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
  to: 'test@example.com',
  from: 'test@example.com',
  subject: 'Sending with Twilio SendGrid is Fun',
  text: 'and easy to do anywhere, even with Node.js',
  html: '<strong>and easy to do anywhere, even with Node.js</strong>',
};
sgMail.send(msg);

【讨论】: