const nodemailer = require('nodemailer');
const redis = require('redis');
// 创建邮件发送器
const transporter = nodemailer.createTransport({
service: 'your-email-service', // 替换为你的邮件服务
auth: {
user: 'your-email@example.com', // 替换为你的邮箱用户名
pass: 'your-email-password' // 替换为你的邮箱密码
}
});
// 创建Redis客户端
const redisClient = redis.createClient({
host: 'localhost', // Redis服务器地址
port: 6379, // Redis服务器端口
// 如果需要密码,使用以下选项
// password: 'your-redis-password'
});
// 生成随机验证码
function generateCode(length) {
let code = '';
const chars = '0123456789';
for (let i = 0; i < length; i++) {
code += chars[Math.floor(Math.random() * chars.length)];
}
return code;
}
// 发送邮件验证码
async function sendEmail(to, code) {
const mailOptions = {
from: 'your-email@example.com', // 发件人邮箱地址
to, // 收件人邮箱地址
subject: 'Email Verification', // 邮件主题
text: `Your verification code is: ${code}` // 邮件文本内容
};
try {
await transporter.sendMail(mailOptions);
console.log('Email sent successfully');
} catch (error) {
console.error('Error sending email: ', error);
}
}
// 验证邮箱验证码
async function verifyCode(email, code) {
const key = `email_code:${email}`;
try {
const storedCode = await redisClient.get(key);
if (code === storedCode) {
console.log('Email verification successful');
// 验证成功后从Redis中删除验证码
await redisClient.del(key);
return true;
} else {
console.log('Email verification failed');
return false;
}
} catch (error) {
console.error('Error verifying code: ', error);
return false;
}
}
// 示例:生成验证码并发送邮件
async function sendEmailWithCode(email) {
const code = generateCode(6); // 生成6位随机验证码
const key = `email_code:${email}`;
try {
// 将验证码存储到Redis,并设置过期时间
await redisClient.set(key, code);
await redisClient.expire(key, 300); // 设置验证码有效期为300秒
// 发送邮件
await sendEmail(email, code);
} catch (error) {
console.error('Error sending email with
评论已关闭