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

运行SendGrid代码时遇Error: Cannot find module 'sendgrid'问题求助

Fixing "Error: Cannot find module 'sendgrid'" in Your Node.js Code

Hey there! Let's break down what's going on here. Even though you mentioned you haven't used SendGrid before, your code is explicitly trying to import and use the SendGrid library—that's exactly why Node.js is throwing the "Cannot find module" error: it can't locate the SendGrid package in your project's dependencies.

Here's how to fix this step by step:

1. Install the official, maintained SendGrid package

The old sendgrid package is deprecated now; the current official package is @sendgrid/mail. Run this command in your project directory to install it:

npm install @sendgrid/mail

2. Update your code to match the modern package syntax

Your code uses an outdated pattern for SendGrid. Here's the corrected version that works with the current package:

// Replace <key> with your actual SendGrid API key
const SENDGRID_API_KEY = "<key>"; 
const sgMail = require('@sendgrid/mail');

// Set your API key
sgMail.setApiKey(SENDGRID_API_KEY);

const msg = { 
  to: "eden.cmo@gmail.com", // Your recipient email
  from: "test.test@gmail.com", // Ensure this is a verified sender in your SendGrid account
  subject: "Sending with 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) 
  .then(() => { 
    console.log("Email sent"); 
  }) 
  .catch((error) => { 
    console.error(error); 
}); 

Why the original error happened:

Node.js looks for installed packages in your project's node_modules folder. Since you hadn't installed the SendGrid package (and were referencing a deprecated version that wasn't present), it couldn't locate the module and threw the MODULE_NOT_FOUND error.

Quick side note: Don't forget to verify your "from" email address in the SendGrid dashboard—otherwise, SendGrid will block the email from being sent!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 21:08:12