运行SendGrid代码时遇Error: Cannot find module 'sendgrid'问题求助
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

