我正在使用sendGrid电子邮件通过nodeJS发送Web api邮件。虽然我能够成功发送邮件,但它们仍在垃圾邮件文件夹中。
以前,我曾尝试使用phpmailer函数使用php发送电子邮件,这些电子邮件已成功发送到用户的收件箱中。
下面是我的代码:
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
const MongoClient = require('mongodb').MongoClient;
const env = require('dotenv').config();
const sgMail = require('@sendgrid/mail');
var dburl = process.env.URL;
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({extended:true}));
router.post('/users', (req,res) => {
var data = {
_id:req.body.id,
Name:req.body.username,
Email:req.body.email
};
const msg = {
to: 'example@gmail.com',
from: 'test@gmail.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>'
};
MongoClient.connect(dburl,{ useNewUrlParser: true }, (err,client) => {
if(err){
console.log('Unable to connect with database'.red +err);
}
else{
client.db("Example").collection("Users").findOne({_id:req.body.id},function(err,user) {
if(err){
console.log("Error:".red +err);
}
if(user){
res.send("User exists");
}
else{
var collection = client.db("Example").collection("Users");
collection.insertOne(data,(err,resp) => {
if(err){
console.log("Insertion error".red +err);
}
else{
res.send("User created");
sgMail.send(msg,(err) => {
if(err){
console.log("Error",err);
}else{
console.log("Mail sent");
}
});
}
});
}
client.close();
});
}
});
});
module.exports = router;
有人让我知道如何将电子邮件发送到用户收件箱。我们将不胜感激。
谢谢