const tools = require('./tools/general'); require('./config/config'); const Email = require('email-templates'); var i18n = require("i18n"); const { ObjectID } = require('mongodb'); const { Settings } = require('./models/settings'); const previewEmail = require('preview-email'); const nodemailer = require("nodemailer"); const { MyEvent } = require('./models/myevent'); const { MailingList } = require('./models/mailinglist'); const { Newstosent } = require('./models/newstosent'); const transport_preview = nodemailer.createTransport({ jsonTransport: true }); // create reusable transport method (opens pool of SMTP connections) var smtpTransport = nodemailer.createTransport({ service: 'Gmail', auth: { user: process.env.EMAIL_FROM, pass: process.env.EMAIL_PW } }); function checkifSendEmail() { return process.env.SEND_EMAIL === "1"; //return false; } module.exports = { sendEmail_base: function (template, to, mylocalsconf, replyTo) { console.log('mylocalsconf', mylocalsconf); // console.log("check EMAIL :" + checkifSendEmail()); const email = new Email({ message: { from: process.env.EMAIL_FROM, // sender address headers: { 'Reply-To': replyTo } }, send: checkifSendEmail(), preview: !checkifSendEmail(), transport: { service: 'Gmail', auth: { user: process.env.EMAIL_FROM, pass: process.env.EMAIL_PW } }, // htmlToText: false }); return email .send({ template: template, message: { to: to, }, locals: mylocalsconf, }) .then((ris) => { return !!ris }) .catch((err) => { console.error(err); return false }); }, sendEmail_Normale: function (to, subject, html, replyTo) { // setup e-mail data with unicode symbols var mailOptions = { from: process.env.EMAIL_FROM, // sender address to: to, generateTextFromHTML: true, subject: subject, html: html, }; if (replyTo) mailOptions['reply-to'] = replyTo; if (process.env.SEND_EMAIL === 1) { console.log("SEND EMAIL smtpTransport"); // send mail with defined transport object smtpTransport.sendMail(mailOptions, function (error, response) { if (error) { console.log(error); } else { console.log("Message sent: " + response); } }); } else { if (process.env.PROVA_EMAIL_TEMPLATE !== "1") previewEmail(mailOptions).then(console.log).catch(console.error); else transport_preview.sendMail(mailOptions).then(console.log).catch(console.error); } }, // getHostByIdApp: function (idapp) { // if (idapp === 1) { // let siteport = (process.env.PORT_APP1 !== "0") ? (':' + process.env.PORT_APP1) : ""; // return process.env.URLBASE_APP1 + siteport; // } else { // return "" // } // }, getlinkReg: function (idapp, idreg) { strlinkreg = tools.getHostByIdApp(idapp) + process.env.LINKVERIF_REG + `?idapp=${idapp}&idlink=${idreg}`; return strlinkreg; }, getlinkRequestNewPassword: function (idapp, user, tokenforgot) { strlinkreg = tools.getHostByIdApp(idapp) + "/#" + process.env.LINK_REQUEST_NEWPASSWORD + `?idapp=${idapp}&username=${user}&=tokenforgot=${tokenforgot}`; return strlinkreg; }, sendEmail_Registration: function (lang, emailto, user, idapp, idreg) { console.log('idapp', idapp, tools.getNomeAppByIdApp(idapp)); mylocalsconf = { locale: lang, nomeapp: tools.getNomeAppByIdApp(idapp), strlinkreg: this.getlinkReg(idapp, idreg), username: user.username, name: user.name, surname: user.surname, forgetpwd: "", emailto: emailto, }; this.sendEmail_base('registration/' + lang, emailto, mylocalsconf, tools.getreplyToEmailByIdApp(idapp)); // Send to the Admin an Email this.sendEmail_base('admin/registration/' + lang, tools.getAdminEmailByIdApp(idapp), mylocalsconf, ''); if (tools.isManagAndAdminDifferent(idapp)) { this.sendEmail_base('admin/registration/' + lang, tools.getManagerEmailByIdApp(idapp), mylocalsconf, ''); } }, sendEmail_RequestNewPassword: function (lang, emailto, idapp, tokenforgot) { mylocalsconf = { locale: lang, nomeapp: tools.getNomeAppByIdApp(idapp), user: user, strlinksetpassword: this.getlinkRequestNewPassword(idapp, user, tokenforgot), emailto: emailto, }; this.sendEmail_base('resetpwd/' + lang, emailto, mylocalsconf, ''); }, sendEmail_Booking: function (res, lang, emailto, user, idapp, recbooking) { tools.mylog('sendEmail_Booking'); tools.mylog('tools.getNomeAppByIdApp(idapp)', tools.getNomeAppByIdApp(idapp), idapp); mylocalsconf = { locale: lang, nomeapp: tools.getNomeAppByIdApp(idapp), name: user.name, surname: user.surname, emailto: emailto, participants: '', msgbooking: tools.convertTexttoHtml(recbooking.msgbooking), eventtextplain: tools.removeSpecialCharForEmail(recbooking.infoevent), event: recbooking.infoevent, }; return Settings.getValDbSettings(idapp, 'MSG_REPLY_AFTER_BOOKING').then((ris => { mylocalsconf.msgreply_after_booking = ris; if (recbooking.numpeople > 1) mylocalsconf.participants = recbooking.numpeople.toString() + ' ' + res.__("partecipanti"); let texthtml = ''; if (recbooking.modified) { texthtml = 'modifybooking'; } else { texthtml = 'makebooking'; } this.sendEmail_base('booking/' + texthtml + '/' + lang, emailto, mylocalsconf, tools.getreplyToEmailByIdApp(idapp)); // Send Email also to the Admin this.sendEmail_base('admin/' + texthtml + '/' + lang, tools.getAdminEmailByIdApp(idapp), mylocalsconf, ''); if (tools.isManagAndAdminDifferent(idapp)) { this.sendEmail_base('admin/' + texthtml + '/' + lang, tools.getManagerEmailByIdApp(idapp), mylocalsconf, ''); } })); }, sendEmail_CancelBooking: function (res, lang, emailto, user, idapp, recbooking) { tools.mylog('sendEmail_CancelBooking'); mylocalsconf = { locale: lang, nomeapp: tools.getNomeAppByIdApp(idapp), name: user.name, surname: user.surname, emailto: emailto, event: recbooking.infoevent, participants: '', eventtextplain: tools.removeSpecialCharForEmail(recbooking.infoevent), }; if (recbooking.numpeople > 1) mylocalsconf.participants = recbooking.numpeople.toString() + ' ' + res.__("partecipanti"); this.sendEmail_base('booking/cancelbooking/' + lang, emailto, mylocalsconf, tools.getreplyToEmailByIdApp(idapp)); // Send Email also to the Admin this.sendEmail_base('admin/cancelbooking/' + lang, tools.getAdminEmailByIdApp(idapp), mylocalsconf, ''); if (tools.isManagAndAdminDifferent(idapp)) { this.sendEmail_base('admin/cancelbooking/' + lang, tools.getManagerEmailByIdApp(idapp), mylocalsconf, ''); } }, sendEmail_Msg: function (res, lang, emailto, user, idapp, recmsg) { tools.mylog('sendEmail_Msg'); tools.mylog('tools.getNomeAppByIdApp(idapp)', tools.getNomeAppByIdApp(idapp), idapp); mylocalsconf = { locale: lang, nomeapp: tools.getNomeAppByIdApp(idapp), name: user.name, surname: user.surname, usernameorig: user.name + ' ' + user.surname, emailto: emailto, message: tools.convertTexttoHtml(recmsg.message), infoevent: recmsg.source.infoevent, strlinkreply: tools.getHostByIdApp(idapp) + '/messages/' + recmsg._id }; let replyto = ''; if (mylocalsconf.infoevent !== '') replyto = user.email; else replyto = tools.getreplyToEmailByIdApp(idapp); return this.sendEmail_base('msg/sendmsg/' + lang, emailto, mylocalsconf, replyto); // Send Email also to the Admin // this.sendEmail_base('admin/sendmsg/' + lang, tools.getAdminEmailByIdApp(idapp), mylocalsconf); }, sendEmail_Notif_Added_to_Newsletter: function (lang, user, idapp) { console.log('idapp', idapp, tools.getNomeAppByIdApp(idapp)); mylocalsconf = { locale: lang, nomeapp: tools.getNomeAppByIdApp(idapp), name: user.name, surname: user.surname, emailto: user.email, }; // Add to the database myperson = new MailingList({ name: mylocalsconf.name, surname: mylocalsconf.surname, email: mylocalsconf.emailto }); myperson._id = new ObjectID(); myperson.idapp = idapp; // Add new record to the DB MailingList return myperson.save().then((res) => { // Send to the Admin an Email this.sendEmail_base('admin/added_to_newsletter/' + lang, tools.getAdminEmailByIdApp(idapp), mylocalsconf, ''); if (tools.isManagAndAdminDifferent(idapp)) { this.sendEmail_base('admin/added_to_newsletter/' + lang, tools.getManagerEmailByIdApp(idapp), mylocalsconf, ''); } }); }, sendEmail_Newsletter_Events: async function (lang, idapp, id_newstosent) { console.log('INIZIO - sendEmail_Newsletter_Events', tools.getNomeAppByIdApp(idapp)); //++Todo Extract List Email to send const userstosend = await MailingList.findAllIdApp(idapp); const myarrevents = await MyEvent.getLastEvents(idapp); mylocalsconf = { locale: lang, nomeapp: tools.getNomeAppByIdApp(idapp), arrevents: myarrevents }; const mynewsrec = await Newstosent.findOne({ _id: id_newstosent }); mynewsrec.numemail_tot = userstosend.length; for (const user of userstosend) { mylocalsconf.name = user.name; mylocalsconf.surname = user.surname; mylocalsconf.emailto = user.email; // If has already sent, don't send it again! if (user.lastid_newstosent !== id_newstosent.toString()) { // Send Email to the User console.log('-> Invio Email (', mynewsrec.numemail_sent, '/', mynewsrec.numemail_tot, ')'); const esito = this.sendEmail_base('newsletter/' + lang, tools.getAdminEmailByIdApp(idapp), mylocalsconf, ''); //Put the result in the database, to check if is sent or not. const updateml = await MailingList.findOneAndUpdate({ idapp, email: user.email }, { $set: { lastid_newstosent: ObjectID(id_newstosent) } }, { new: false }); mynewsrec.lastemailsent_Job = new Date(); mynewsrec.numemail_sent += 1; const recsaved = await mynewsrec.save(); //Delay for send email... await tools.snooze(process.env.DELAY_SENDEMAIL); if (mynewsrec.numemail_sent === mynewsrec.numemail_tot) { mynewsrec.datefinishJob = new Date(); mynewsrec.finish_job = true; await mynewsrec.save().then((ris) => { console.log('****', tools.getNomeAppByIdApp(idapp), mynewsrec.numemail_sent, 'Email inviate'); }); } } } console.log('FINE (esco da funz) - sendEmail_Newsletter_Events', tools.getNomeAppByIdApp(idapp)); }, checkifSentNewsletter: async function (idapp) { // Check if is the time to send the Newsletter return Newstosent.findNewsletter_To_Send(idapp) .then((rec) => { if (rec) this.sendNewsletter(rec); }); } , checkifPendingNewsletter: async function (idapp) { // Check if is the time to send the Newsletter // Only newsletter pending en 8 hour last email sent. return Newstosent.findNewsletterPending_To_Send(idapp) .then((rec) => { // this.sendNewsletter(rec) }); }, sendNewsletter: async function (rec) { // Start the job myjobnews = await Newstosent.findOne({ _id: rec._id }); if (!!myjobnews) { myjobnews.starting_job = true; myjobnews.datestartJob = new Date(); myjobnews.save() .then((ris) => { this.sendEmail_Newsletter_Events("it", '2', rec._id); }) .catch((e) => { console.error(e); }); } }, testemail: async function (idapp, lang) { const myarrevents = await MyEvent.getLastEvents(idapp); mylocalsconf = { locale: lang, nomeapp: tools.getNomeAppByIdApp(idapp), arrevents: myarrevents, name: 'Paolo', surname: 'Arena', emailto: "pa.oloarena77@gmail.com", }; console.log('-> Invio Email TEST a', mylocalsconf.emailto); return this.sendEmail_base('newsletter/' + lang, tools.getAdminEmailByIdApp(idapp), mylocalsconf, ''); } } ;