@jackiemacklein/nettz-utils
Version:
Serviços de imagem, e-mail, códigos de barras, utilitários numéricos e componentes React para apps Node.js com TypeScript
261 lines (260 loc) • 10.7 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const nodemailer_1 = __importDefault(require("nodemailer"));
class EmailService {
constructor() {
this.parameters = {
SMTP_FROM_EMAIL: "",
SMTP_FROM_NAME: "",
// SMTP_INTEGRATION: "",
SMTP_PROVIDER: "SMTP",
SMTP_HOST: "",
SMTP_PORT: "",
SMTP_SECURITY: "TLS",
SMTP_USERNAME: "",
SMTP_PASSWORD: "",
};
}
static getInstance() {
if (!EmailService.instance) {
EmailService.instance = new EmailService();
}
return EmailService.instance;
}
/**
* @param params - Parâmetros de configuração do email
*/
setParameters(params) {
this.parameters = params;
}
getParameter(key) {
return this.parameters[key] || "";
}
getSmtpProvider() {
return this.getParameter("SMTP_PROVIDER");
}
async sendViaNodemailer(options, log = false) {
if (log)
console.log("[NETTZ MAIL] => sendViaNodemailer => options => ", options);
try {
const provider = this.getSmtpProvider();
let transportConfig = {};
if (log)
console.log("[NETTZ MAIL] => sendViaNodemailer => provider => ", provider);
if (["Gmail", "Outlook", "SMTP"].includes(provider)) {
transportConfig = {
host: this.getParameter("SMTP_HOST"),
port: parseInt(this.getParameter("SMTP_PORT")),
secure: this.getParameter("SMTP_SECURITY") === "SSL",
auth: {
user: this.getParameter("SMTP_USERNAME"),
pass: this.getParameter("SMTP_PASSWORD"),
},
};
if (log)
console.log("[NETTZ MAIL] => sendViaNodemailer => transportConfig => ", transportConfig);
// Configuração adicional para STARTTLS
if (this.getParameter("SMTP_SECURITY") === "STARTTLS") {
transportConfig.requireTLS = true;
transportConfig.secure = false;
if (log)
console.log("[NETTZ MAIL] => sendViaNodemailer => transportConfig => secure => ", transportConfig.secure);
}
}
else if (provider === "Brevo") {
// Configuração específica para Brevo (usando SMTP)
transportConfig = {
host: "smtp-relay.brevo.com",
port: 587,
secure: false,
auth: {
user: this.getParameter("SMTP_USERNAME"),
pass: this.getParameter("SMTP_PASSWORD"),
},
};
if (log)
console.log("[NETTZ MAIL] => sendViaNodemailer => Brevo => transportConfig => ", transportConfig);
}
const transporter = nodemailer_1.default.createTransport(transportConfig);
const mailOptions = {
from: {
name: this.getParameter("SMTP_FROM_NAME"),
address: this.getParameter("SMTP_FROM_EMAIL"),
},
to: options.to,
cc: options.cc,
bcc: options.bcc,
subject: options.subject,
text: options.text,
html: options.html,
attachments: options.attachments,
};
if (log)
console.log("[NETTZ MAIL] => sendViaNodemailer => mailOptions => ", mailOptions);
const info = await transporter.sendMail(mailOptions);
if (log)
console.log("[NETTZ MAIL] => sendViaNodemailer => Email enviado:", info.messageId);
return true;
}
catch (error) {
if (log)
console.error("[NETTZ MAIL] => sendViaNodemailer => Erro ao enviar email via SMTP:", error);
throw error;
}
}
// private async sendViaBrevoApi(options: EmailOptions): Promise<boolean> {
// try {
// const apiKey = this.getParameter("SMTP_API_KEY");
// const baseUrl = this.getParameter("SMTP_BASE_URL") || "https://api.brevo.com/v3";
// const recipients = Array.isArray(options.to) ? options.to : [options.to];
// const payload = {
// sender: {
// name: this.getParameter("SMTP_FROM_NAME"),
// email: this.getParameter("SMTP_FROM_EMAIL"),
// },
// to: recipients.map(email => ({ email })),
// subject: options.subject,
// htmlContent: options.html,
// textContent: options.text,
// };
// // Adicionar CC se existir
// if (options.cc) {
// const ccRecipients = Array.isArray(options.cc) ? options.cc : [options.cc];
// payload["cc"] = ccRecipients.map(email => ({ email }));
// }
// // Adicionar BCC se existir
// if (options.bcc) {
// const bccRecipients = Array.isArray(options.bcc) ? options.bcc : [options.bcc];
// payload["bcc"] = bccRecipients.map(email => ({ email }));
// }
// // Adicionar anexos se existirem
// if (options.attachments && options.attachments.length > 0) {
// payload["attachment"] = options.attachments.map(attachment => ({
// name: attachment.filename,
// content: typeof attachment.content === "string" ? attachment.content : attachment.content.toString("base64"),
// contentType: attachment.contentType,
// }));
// }
// const response = await axios.post(`${baseUrl}/smtp/email`, payload, {
// headers: {
// "api-key": apiKey,
// "Content-Type": "application/json",
// },
// });
// console.log("Email enviado via API Brevo:", response.data);
// return true;
// } catch (error) {
// console.error("Erro ao enviar email via API Brevo:", error);
// return false;
// }
// }
/**
* @param options - Opções de envio do email
* @param log - Se deve mostrar o log das informações do email
* @returns - Promise que resolve com true se o email foi enviado com sucesso, false caso contrário
*/
async sendEmail(options, log = false) {
if (log)
console.log("[NETTZ MAIL] => sendEmail => options => ", options);
// const provider = this.getSmtpProvider();
// // Usar API para Brevo se configurado para usar API
// if (provider === "Brevo" && this.getParameter("SMTP_BASE_URL")) {
// return this.sendViaBrevoApi(options);
// }
// Usar SMTP para todos os outros casos
return this.sendViaNodemailer(options, log);
}
// Método de conveniência para enviar emails simples
/**
* @param to - Email do destinatário
* @param subject - Assunto do email
* @param message - Mensagem do email
* @param isHtml - Se a mensagem é HTML
* @param log - Se deve mostrar o log das informações do email
* @returns - Promise que resolve com true se o email foi enviado com sucesso, false caso contrário
*/
async sendSimpleEmail(to, subject, message, isHtml = false, log = false) {
const options = {
to,
subject,
};
if (isHtml) {
options.html = message;
}
else {
options.text = message;
}
return this.sendEmail(options, log);
}
// Método para testar a conexão SMTP
/**
* @returns - Promise que resolve com true se a conexão SMTP foi estabelecida com sucesso, false caso contrário
*/
async testConnection() {
try {
const provider = this.getSmtpProvider();
// if (provider === "Brevo" && this.getParameter("SMTP_BASE_URL")) {
// // Testar API Brevo
// const apiKey = this.getParameter("SMTP_API_KEY");
// const baseUrl = this.getParameter("SMTP_BASE_URL") || "https://api.brevo.com/v3";
// const response = await axios.get(`${baseUrl}/account`, {
// headers: {
// "api-key": apiKey,
// },
// });
// if (response.status === 200) {
// return {
// success: true,
// message: `Conexão com API Brevo estabelecida com sucesso. Conta: ${response.data.email}`,
// };
// }
// } else {
// Testar SMTP
let transportConfig = {};
if (["Gmail", "Outlook", "SMTP"].includes(provider)) {
transportConfig = {
host: this.getParameter("SMTP_HOST"),
port: parseInt(this.getParameter("SMTP_PORT")),
secure: this.getParameter("SMTP_SECURITY") === "SSL",
auth: {
user: this.getParameter("SMTP_USERNAME"),
pass: this.getParameter("SMTP_PASSWORD"),
},
};
}
else if (provider === "Brevo") {
transportConfig = {
host: "smtp-relay.brevo.com",
port: 587,
secure: false,
auth: {
user: this.getParameter("SMTP_USERNAME"),
pass: this.getParameter("SMTP_PASSWORD"),
},
};
}
const transporter = nodemailer_1.default.createTransport(transportConfig);
await transporter.verify();
return {
success: true,
message: "Conexão SMTP estabelecida com sucesso.",
};
// }
// return {
// success: false,
// message: "Não foi possível verificar a conexão.",
// };
}
catch (error) {
console.error("Erro ao testar conexão:", error);
throw {
error: "CONNECTION_ERROR",
message: `Erro ao testar conexão: ${error.message || "Erro desconhecido"}`,
};
}
}
}
exports.default = EmailService.getInstance();