简体   繁体   中英

Sendgrid import issue in firebase-functions

I have this issue where sendgrid does not seem to be imported in a firebase function.

I have this helper function to send mails like this:

import * as sgMail from "@sendgrid/mail";
import {logger} from "firebase-functions";

let sendgridInitialized = false;
export const ensureSendgridIsInitialized = () => {
  if (sendgridInitialized) {
    return;
  }
  const apiKey = process.env.SENDGRID_API_KEY;
  if (!apiKey) {
    throw new Error("SENDGRID_API_KEY env key missing");
  }
  sgMail.setApiKey(apiKey);
  sendgridInitialized = true;
};

export async function sendEmailFromMessage(
  message: sgMail.MailDataRequired | sgMail.MailDataRequired[]
) {
  ensureSendgridIsInitialized();
  logger.log("Sending mail", {message});
  try {
    await sgMail.send(message);
  } catch (error) {
    logger.error("Error sending email", error);
  }
}

Now I get the following issue: sgMail.setApiKey is not a function

Anyone encounter this?

In my package.json :

Node: 16
firebase-functions: "^3.21.0"
@sendgrid/mail: "^7.7.0"

Try without ”” and it should look like this:

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

The exports from that file are exported as a new object called sgMail. To use that syntax, you want to:

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

You can also simplify the import of the default instance directly using:

import sgMail from '@sendgrid/mail'

Or you can use the code from the npmjs website:

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);

Also, the sendgrid github uses the same code as a quickstart code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM