full
This commit is contained in:
80
utils/emailService.js
Normal file
80
utils/emailService.js
Normal file
@@ -0,0 +1,80 @@
|
||||
let nodemailer = null
|
||||
try {
|
||||
nodemailer = require('nodemailer')
|
||||
} catch (error) {
|
||||
console.warn('[emailService] nodemailer not installed:', error.message)
|
||||
}
|
||||
|
||||
let transporter = null
|
||||
|
||||
function getTransporter () {
|
||||
if (!nodemailer) return null
|
||||
if (transporter) return transporter
|
||||
|
||||
const host = process.env.SMTP_HOST
|
||||
const port = Number(process.env.SMTP_PORT || 587)
|
||||
const user = process.env.SMTP_USER
|
||||
const pass = process.env.SMTP_PASS
|
||||
|
||||
if (!host || !user || !pass) {
|
||||
return null
|
||||
}
|
||||
|
||||
transporter = nodemailer.createTransport({
|
||||
host,
|
||||
port,
|
||||
secure: port === 465,
|
||||
auth: { user, pass }
|
||||
})
|
||||
|
||||
return transporter
|
||||
}
|
||||
|
||||
function isEmailConfigured () {
|
||||
return Boolean(nodemailer && getTransporter())
|
||||
}
|
||||
|
||||
async function sendEmail ({ to, subject, text, html }) {
|
||||
const mailer = getTransporter()
|
||||
if (!mailer) {
|
||||
console.warn('[emailService] SMTP is not configured. Email not sent to:', to)
|
||||
return false
|
||||
}
|
||||
|
||||
await mailer.sendMail({
|
||||
from: process.env.SMTP_FROM || process.env.SMTP_USER,
|
||||
to,
|
||||
subject,
|
||||
text,
|
||||
html
|
||||
})
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
async function sendOtpEmail (to, otp, purpose = 'verification') {
|
||||
const subjectMap = {
|
||||
verification: 'کد تایید مدستاگرام',
|
||||
password_reset: 'بازیابی کلمه عبور مدستاگرام'
|
||||
}
|
||||
|
||||
const subject = subjectMap[purpose] || subjectMap.verification
|
||||
const text = `کد تایید شما: ${otp}\n\nاین کد تا ۲ دقیقه معتبر است.\nمدستاگرام`
|
||||
const html = `
|
||||
<div dir="rtl" style="font-family:Tahoma,sans-serif;line-height:1.8">
|
||||
<h2>${subject}</h2>
|
||||
<p>کد تایید شما:</p>
|
||||
<p style="font-size:24px;font-weight:bold;letter-spacing:4px">${otp}</p>
|
||||
<p>این کد تا ۲ دقیقه معتبر است.</p>
|
||||
<p>مدستاگرام</p>
|
||||
</div>
|
||||
`
|
||||
|
||||
return sendEmail({ to, subject, text, html })
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
isEmailConfigured,
|
||||
sendEmail,
|
||||
sendOtpEmail
|
||||
}
|
||||
Reference in New Issue
Block a user