我有一个包含 4 个字段的简单表单,即:
- 姓名
- 出生日期
- 电子邮件地址
- 信息
我将这些数据保存到 mongodb。生日那天,我需要发送电子邮件提醒。我使用 node_mailer 发送邮件。但是如何设置在特定日期发送邮件的提醒呢?我正在运行 nodejs 服务器。
谢谢
我有一个包含 4 个字段的简单表单,即:
我将这些数据保存到 mongodb。生日那天,我需要发送电子邮件提醒。我使用 node_mailer 发送邮件。但是如何设置在特定日期发送邮件的提醒呢?我正在运行 nodejs 服务器。
谢谢
不要使用节点来跟踪这样的日期。不要重新发明轮子。
您的平台,无论是 Mac、Linux 还是 Windows,都有一个调度程序。传统的称为“cron”。使用它来启动 node_mailer 的简单包装器,它将扫描数据库中的“今天的生日”,然后发送电子邮件。
您可以为此使用node-cron。
这只是需要的基本循环
您每天在特定时间循环访问用户,然后检查日期和月份是否匹配并拍摄您的邮件
**这里是下面的示例代码**欢呼
const cron = require('node-cron');
const mailer = require('nodemailer');
//T0 Get the Current Year, Month And Day
var dateYear = new Date().getFullYear();
var dateMonth = new Date().getMonth(); // start counting from 0
var dateDay = new Date().getDate();// start counting from 1
/* The Schema Which The Database Follow
{
'id' : number,
'name' : string,
'dob' : string (day - month),
'email' : string
},
* You can Use Any type of schema (This is the method I preferred)
*/
/// database goes here
var users = [
{
'id' : 000,
'name' : 'user1',
'dob' : '14-6-1994',
'email' : 'user1@exapmle.com'
},
{
'id' : 001,
'name' : 'user2',
'dob' : '15-6-2003',
'email' : 'user2@exapmle.com'
},
{
'id' : 002,
'name' : 'user3',
'dob' : '17-4-2004',
'email' : 'user3@exapmle.com'
},
{
'id' : 003,
'name' : 'user4',
'dob' : '6-0-1999',
'email' : 'user4@exapmle.com'
}
]
//// credentials for your Mail
var transporter = mailer.createTransport({
host: 'YOUR STMP SERVER',
port: 465,
secure: true,
auth: {
user: 'YOUR EMAIL',
pass: 'YOUR PASSWORD'
}
});
//Cron Job to run around 7am Server Time
cron.schedule('* * 07 * * *', () => {
///The Main Function
const sendWishes =
// looping through the users
users.forEach(element => {
// Spliting the Date of Birth (DOB)
// to get the Month And Day
let d = element.dob.split('-')
let dM = +d[1] // For the month
let dD = +d[0] // for the day
let age = dateYear - +d[2]
console.log( typeof dM) //return number
// Sending the Mail
if(dateDay == dD && dateMonth == dM ){
const mailOptions = {
from: 'YOUR EMAIL',
to: element.email,
subject: `Happy Birthday `,
html: `Wishing You a <b>Happy birthday ${element.name}</b> On Your ${age}, Enjoy your day \n <small>this is auto generated</small>`
};
return transporter.sendMail(mailOptions, (error, data) => {
if (error) {
console.log(error)
return
}
});
}
});
});
我发现agendajs非常可靠,并且使用 GUI 补充agenagesh效果更好