Error sending email with Sendgrid in Nodejs

Asked

Viewed 62 times

1

I have the following structure to send emails by SendGrid:

import mail from '@sendgrid/mail';

function send(email_data) {
  mail.setApiKey(process.env.SENDGRID_API_KEY);

  const message = {
    to: email_data.to,
    from: email_data.from,
    subject: email_data.subject,
    text: email_data.text,
  };

  return mail.send(message);
}

export default send;

In my Controller, I call method send as follows:

import mail from '../../services/sendgrid';

    const email_data = {
      to: '[email protected]',
      from: '[email protected]',
      subject: 'Deposito realizado',
      text: 'Foi feito um deposito na sua conta ...',
    };
    
    mail.send(email_data);

But the following error is displayed to me:

(node:7963) UnhandledPromiseRejectionWarning: TypeError: _sendgrid2.default.send is not a function

  • This will probably be import error. You exported the function send as default, but is trying to summon her as mail.send. Include in the code how you imported this module.

  • imported as follows. I put up

1 answer

2


Yes, that’s an import error.

Modules export objects in Javascript, default is only one of the properties of this object. When you import the module, you can choose what you want to import:

// isso importa a propriedade default e a renomeia para metodo_1
import metodo_1 from "modulo"

// isso importa as demais propriedades via desestruturação
import { metodo_2, propriedade_1 } from "modulo"

// isso importa todas as propriedades e as colocam dentro do objeto tudo
// você pode acessa-los como tudo.default, tudo.metodo_2, tudo.propriedade_1
import * as tudo from "modulo"

Like send is being exported as default, when it comes time to care you should do

import send from '../../services/sendgrid';

const email_data = {
  to: '[email protected]',
  from: '[email protected]',
  subject: 'Deposito realizado',
  text: 'Foi feito um deposito na sua conta ...',
};

send(email_data);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.