Reputation: 385
I wanted to send mail using @sendgrid/mail but while I was importing it it is not working. My Code snippet is as below,
import * as sgMail from '@sendgrid/mail';
function sendMail(msg) {
sgMail.setApiKey("API-KEY");
sgMail.send(msg, (err, result) => {
if(err){
console.error(err);
}
console.log(result);
});
}
const obj = {
to: "[email protected]",
from: "[email protected]",
subject: "abc",
text: "abc",
html: "<h1>Working</h1>",
}
sendMail(obj);
This is the code I've did, so now the problem is sgMail.setApiKey is not a function error pops.
If I remove setApiKet then sgMail.send is not a function error pops.
So, If you have any solution then let me know.
Upvotes: 9
Views: 8400
Reputation: 82096
If you look at the source of what you are trying to import, you'll find it exports a default instance of MailService
and a named export of the class itself. When you import via:
import * as sgMail from '@sendgrid/mail';
All the exports from that file are exported as a new object (sgMail
). There are a few ways you can keep this syntax and still do what you want:
// use the default instance which is exported as 'default'
sgMail.default.send(obj);
// explictly create your own instance
const svc = new sgMail.MailService();
svc.send(obj);
However, there is an easier way, and it's simply import the default instance directly
import sgMail from '@sendgrid/mail'
Upvotes: 23
Reputation: 1323
You can try this code this is from npmjs website refer npmjs sendgrid/mail
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);
Upvotes: 3