使用 sendgrid 发送电子邮件 [Node.js]

Sending email with sendgrid [Node.js]

本文关键字:Node js 电子邮件 sendgrid 使用      更新时间:2023-09-26

我使用以下代码发送两封特定的电子邮件,一封给预订客户,另一封给我:

sendgrid.send({
        to:         "client@client.com",
        from:       "me@me.com",
        subject:    "Register confirmation",
        html:           "Some HTML",
    },
    function(err, json) {
        if (err) {
            return console.error(err);
        } 
        else {
            next();
        }
});
sendgrid.send({
        to:         "me@me.com",
        from:       "newRegister@me.com",
        subject:    "NEW RESERVATION!",
        html:       "SOME TEXT OR HTML",
    },
    function(err, json) {
        if (err) {
            return console.error(err);
        } 
        else {
            next();
        }
});

我可以改进吗?有很多重复。

您可以将自己指定为收件人,您将收到客户收到的确切电子邮件。如果您使用 SMTPAPI,用户将看不到您的电子邮件地址,您也看不到他们的电子邮件地址。要在 Node.js lib 中使用它,您可以通过以下方式执行此操作:

var sendgrid = require('sendgrid')('api_user', 'api_pwd');
var email = sendgrid.Email();
email.smtpapi.addTo('client@email.com');
email.smtpapi.addTo('your@notification.email');
email.setSubject('Register confirmation');
email.setHtml('booking numbah');
email.setFrom('your@email.com');
sendgrid.send(email, function(err, json) {
   console.log(arguments);
});

希望对您有所帮助!

只需替换您从 https://app.sendgrid.com/settings/api_keys 获得的API密钥即可。(创建 API 密钥)

..当然,并安装@sendgrid/邮件包。

npm i @sendgrid/邮件 --保存

const sgMail = require("@sendgrid/mail");
const SENGRID_API_KEY = 'Here_Paste_Your_Key'; 
sgMail.setApiKey(SENGRID_API_KEY);
const msg = {
    to: 'to@email.com',
    from: 'from@email.com',
    subject: "Test Subject",
    text: 'Hello World!',
    html: '<strong>Hello World!</strong>',
};
sgMail.send(msg, function(err, info) {
    if (err) {
        console.log("Email Not Sent.");
    } else {
        console.log("Email Sent Success.");
    }
});