尝试将SendGrid与Angular和Node一起使用



使用Angular和SendGrid,我正在尝试发送电子邮件。我正确安装了 NPM 包,但在实现代码时遇到问题。我生成了一个 API 密钥并将其存储在目录中

echo "export SENDGRID_API_KEY='YOUR_API_KEY'" > sendgrid.env
echo "sendgrid.env" >> .gitignore
source ./sendgrid.env

打字稿是:

sgemail(){
const sgMail = require('@sendgrid/mail'); //ERROR: Cannot find name 'require'.
sgMail.setApiKey(process.env.SENDGRID_API_KEY); //ERROR: Cannot find name 'process'.
const msg = {
to: 'test@example.com',
from: 'test@example.com',
subject: 'Sending with 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>',
};
console.log(msg);
sgMail.send(msg);
}

我在单击按钮时触发了它。

Sendgrid在他们的网站上没有关于导入软件包的信息,例如您必须如何使用import { Vibration } from '@ionic-native/vibration';才能使用Ionic的振动包。

您可以尝试使用提取到他们的发送邮件 API 手动发送 POST 请求。并且不要忘记授权标头。下面是一个同样未经测试的 JavaScript 代码片段。填写YOUR_API_KEY并将"收件人电子邮件"更新为其中一封电子邮件。

var payload = {
"personalizations": [
{
"to": [
{
"email": "john@example.com"
}
],
"subject": "Hello, World!"
}
],
"from": {
"email": "from_address@example.com"
},
"content": [
{
"type": "text/plain",
"value": "Hello, World!"
}
]
};
var myHeaders = new Headers({
"Content-Type": "application/json",
"Authorization": "Bearer YOUR_API_KEY",
});
var data = new FormData();
data.append( "json", JSON.stringify( payload ) );
fetch("https://api.sendgrid.com/v3/mail/send",
{
method: "POST",
headers: myHeaders,
body: data
})
.then(function(res){ return res.json(); })
.then(function(data){ console.log( JSON.stringify( data ) ) })

最新更新