Site/server/controllers/emailController.js

100 lines
2.5 KiB
JavaScript

require('dotenv').config();
const express = require('express');
const router = express.Router();
const nodemailer = require('nodemailer');
const transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: Number(process.env.SMTP_PORT || 587),
secure: process.env.SMTP_SECURE === 'true',
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASS
}
});
// Teste de conexão SMTP ao iniciar
transporter.verify(function (error, success) {
if (error) {
console.error('[SMTP] Falha na conexão:', error);
} else {
console.log('[SMTP] Servidor pronto para enviar emails');
}
});
async function EnviarEmailFunc(Para, Assunto, Conteudo, res) {
try {
if (!Para || !Assunto || !Conteudo) {
throw new Error('Para, Assunto e Conteudo são obrigatórios.');
}
const fromEmail = (process.env.SMTP_FROM_EMAIL || '').trim();
const fromName = (process.env.SMTP_FROM_NAME || 'Zendion, INC.').trim();
if (!fromEmail) {
throw new Error('SMTP_FROM_EMAIL não configurado no .env.');
}
const msg = {
to: Para,
from: {
name: fromName,
address: fromEmail
},
subject: Assunto,
text: Conteudo.replace(/<[^>]*>/g, ''),
html: Conteudo
};
const info = await transporter.sendMail(msg);
console.log('[EMAIL] Enviado:', info.messageId);
if (res) {
return res.status(200).send({
sucesso: true,
message: 'Email enviado com sucesso',
messageId: info.messageId
});
}
return {
sucesso: true,
messageId: info.messageId
};
} catch (error) {
console.error('[EMAIL] Erro ao enviar:', error);
if (res) {
return res.status(500).send({
sucesso: false,
message: 'Erro ao enviar o e-mail',
detalhe: error.message
});
}
return {
sucesso: false,
erro: error.message
};
}
}
router.post('/enviarEmail', function (req, res) {
const { Para, Assunto, Conteudo } = req.body;
if (!Para || !Assunto || !Conteudo) {
return res.status(400).send({
error: 'Os campos "Para", "Assunto" e "Conteudo" são obrigatórios.'
});
}
EnviarEmailFunc(Para, Assunto, Conteudo, res);
});
module.exports = {
router,
EnviarEmailFunc
};