我想使用@ sendgrid / mail发送邮件,但是在导入时无法正常工作。我的代码段如下所示,
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: "mail@gmail.com",
from: "no-reply@gmail.com",
subject: "abc",
text: "abc",
html: "<h1>Working</h1>",
}
sendMail(obj);
这是我做的代码,所以现在的问题是sgMail.setApiKey不是弹出的错误消息。
如果我删除setApiKet,则sgMail.send不是弹出的错误消息。
所以,如果您有任何解决方案,请告诉我。
答案 0 :(得分:2)
您可以尝试从npmjs网站获取此代码,请参考npmjs sendgrid/mail
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);
答案 1 :(得分:0)
如果您查看要导入的内容的source,您会发现它导出了MailService
的默认实例和类本身的命名导出。通过以下方式导入时:
import * as sgMail from '@sendgrid/mail';
该文件的所有导出均导出为新对象(sgMail
)。您可以通过几种方法保留此语法,然后仍然执行所需操作:
// 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);
但是,有一种更简单的方法,它只是直接导入 default 实例
import sgMail from '@sendgrid/mail'