Search code examples
node.jssendgrid

sendGrid mail does not works with import


const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
  to: '[email protected]',
  from: '[email protected]',
  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);

The above uses require to import sendgrid. The above code works.

But as I am using ES6 syntax, I can't use require and have to use import instead.

import sgMail from '@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
  to: '[email protected]',
  from: '[email protected]',
  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);

So, I wrote this code, but it gives error as variable is undefined (reading setApiKey). And when I remove that line. It gives error as variable is undefined (reading send).


Solution

  • Try to import the MailService property:

    import { MailService } from "@sendgrid/mail";
    
    const sendgridClient = new MailService();
    
    sendgridClient.setApiKey(process.env.SENDGRID_API_KEY || "");