Kun*_*iya 0 javascript node.js sendgrid
我想使用@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);
Run Code Online (Sandbox Code Playgroud)
这是我所做的代码,所以现在的问题是 sgMail.setApiKey is not a function error pops。
如果我删除 setApiKet 然后 sgMail.send 不是函数错误弹出。
所以,如果您有任何解决方案,请告诉我。
如果查看要导入的内容的来源,您会发现它MailService导出了类本身的默认实例和命名导出。当您通过以下方式导入时:
import * as sgMail from '@sendgrid/mail';
Run Code Online (Sandbox Code Playgroud)
该文件的所有导出都导出为新对象 ( 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);
Run Code Online (Sandbox Code Playgroud)
但是,还有一个更简单的方法,那就是直接导入默认实例
import sgMail from '@sendgrid/mail'
Run Code Online (Sandbox Code Playgroud)
您可以尝试此代码,该代码来自 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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
850 次 |
| 最近记录: |