meily
Version:
Meily es un paquete minimalista para el envío de correos electrónicos en Node.js utilizando nodemailer, con soporte para plantillas HTML basadas en Handlebars y una sintaxis fluida y sencilla.
124 lines (103 loc) • 2.6 kB
JavaScript
'use strict';
var nodemailer = require('nodemailer');
var arrowyEnv = require('arrowy-env');
var fs = require('fs');
var handlebars = require('handlebars');
const transporter = nodemailer.createTransport({
host: arrowyEnv.env('MAIL_HOST'),
port: arrowyEnv.env('MAIL_PORT'),
secure: arrowyEnv.env('MAIL_SECURE') === 'true' ? true : false,
auth: {
user: arrowyEnv.env('MAIL_FROM'),
pass: arrowyEnv.env('MAIL_PASSWORD')
},
tls: { rejectUnauthorized: false }
});
transporter.verify(function (error, success) {
if (error) {
console.log(error);
} else {
console.log('Server is ready to take our messages');
}
});
/**
* @example
* ```js
* Mail.from('cristian.guzman.contacto@gmail.com')
* .to('cristianguzmansuarez@gmail.com')
* .subject('Mi asunto')
* .content('<h1>prueba Email</h1>')
* .send()
* ```
*/
class Mail {
constructor(sender) {
this.theSender = sender;
this.theAttachments = [];
}
static from(sender) {
return new Mail(sender)
}
to(recipient) {
this.theRecipient = recipient;
return this;
}
subject(subject) {
this.theSubject = subject;
return this;
}
content(content) {
this.theContent = content;
return this
}
onError(error) {
throw error
}
attachments(attachments = []) {
this.theAttachments = attachments;
return this
}
onSuccess(info) {
console.log('Correo enviado: ' + info.response);
}
data(data) {
this.theData = data;
return this
}
cc(cc) {
this.theCc = cc;
return this
}
bcc(bcc) {
this.theBcc = bcc;
return this
}
html(html) {
this.theHtml = html;
return this
}
send() {
if (this.theHtml) {
let htmlFile = fs.readFileSync(this.theHtml, 'utf-8');
htmlFile = handlebars.compile(htmlFile)(this.theData);
this.content(htmlFile);
}
const mailOptions = {
from: arrowyEnv.env('MAIL_FROM'),
to: this.theRecipient,
cc: this.theCc,
bcc: this.theBcc,
subject: this.theSubject,
html: this.theContent,
attachments: this.theAttachments
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
this.onError(error);
} else {
this.onSuccess(info);
}
});
}
}
exports.Mail = Mail;