Files
freeplanet_serverside/src/server/sendemail.js
Paolo Arena 512a8c14e2 - Downline User
- Not registered if already exists.
- Forgot Password
2020-01-30 01:19:25 +01:00

657 lines
22 KiB
JavaScript

const tools = require('./tools/general');
const telegrambot = require('./telegram/telegrambot');
require('./config/config');
const Email = require('email-templates');
const i18n = require("i18n");
const { ObjectID } = require('mongodb');
const { Settings } = require('./models/settings');
const { TemplEmail } = require('./models/templemail');
const { Discipline } = require('./models/discipline');
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 server_constants = require('./tools/server_constants');
const transport_preview = nodemailer.createTransport({
jsonTransport: true
});
function checkifSendEmail() {
return process.env.SEND_EMAIL === "1";
//return false;
}
module.exports = {
sendEmail_base: function (template, to, mylocalsconf, replyTo, transport, previewonly) {
// console.log('mylocalsconf', mylocalsconf);
// console.log("check EMAIL :" + checkifSendEmail());
if (replyTo === '')
replyTo = mylocalsconf.dataemail.email_reply;
const paramemail = {
message: {
from: mylocalsconf.dataemail.from, // sender address
headers: {
'Reply-To': replyTo
}
},
};
if (previewonly === undefined) {
paramemail.preview = !checkifSendEmail();
paramemail.send = checkifSendEmail();
} else {
paramemail.preview = previewonly;
paramemail.send = !previewonly;
}
// if (!transport) {
// transport = this.getTransport(mylocalsconf);
// }
// console.log('1 . transport', transport);
if (transport) {
paramemail.transport = transport;
} else {
// console.log('1b . transport gmail');
paramemail.transport = {
service: 'gmail',
auth: {
user: tools.getEmailByIdApp(mylocalsconf.idapp),
pass: tools.getPwdByIdApp(mylocalsconf.idapp)
}
}
}
// console.log('2 . paramemail.transport', paramemail.transport);
// console.log('user', tools.getEmailByIdApp(mylocalsconf.idapp));
// console.log('pass', tools.getPwdByIdApp(mylocalsconf.idapp));
// console.log('paramemail', paramemail);
const email = new Email(paramemail);
return email
.send({
template: template,
message: {
to: to,
},
locals: mylocalsconf,
})
.then((ris) => {
// console.log('ris EMAIL', ris);
return !!ris
})
.catch((err) => {
console.error('sendEmail_base Error: ', err);
return false
});
},
sendEmail_Normale: function (to, subject, html, replyTo) {
// setup e-mail data with unicode symbols
var mailOptions = {
from: tools.getEmailByIdApp(mylocalsconf.idapp), // 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...");
// send mail with defined transport object
smtpTransport.sendMail(mailOptions, function (error, response) {
if (error) {
console.log("Email Inviata ERRORE RISPOSTA: " + error);
} else {
// console.log("Email Inviata RISPOSTA: " + 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, email, tokenforgot) {
strlinkreg = tools.getHostByIdApp(idapp) + process.env.LINK_UPDATE_PASSWORD + `?idapp=${idapp}&email=${email}&tokenforgot=${tokenforgot}`;
return strlinkreg;
},
sendEmail_Registration: async function (lang, emailto, user, idapp, idreg) {
// console.log('idapp', idapp, tools.getNomeAppByIdApp(idapp));
mylocalsconf = {
idapp,
dataemail: await this.getdataemail(idapp),
locale: lang,
nomeapp: tools.getNomeAppByIdApp(idapp),
strlinkreg: this.getlinkReg(idapp, idreg),
username: user.username,
name: user.name,
surname: user.surname,
forgetpwd: "",
emailto: emailto,
user,
};
this.sendEmail_base('registration/' + lang, emailto, mylocalsconf, tools.getreplyToEmailByIdApp(idapp));
// Send to the Admin an Email
this.sendEmail_base('admin/registration/' + tools.LANGADMIN, tools.getAdminEmailByIdApp(idapp), mylocalsconf, '');
await telegrambot.notifyToTelegram(telegrambot.phase.REGISTRATION, mylocalsconf);
if (tools.isManagAndAdminDifferent(idapp)) {
this.sendEmail_base('admin/registration/' + tools.LANGADMIN, tools.getManagerEmailByIdApp(idapp), mylocalsconf, '');
}
},
sendEmail_RequestNewPassword: async function (lang, user, emailto, idapp, tokenforgot) {
mylocalsconf = {
idapp,
dataemail: await this.getdataemail(idapp),
locale: lang,
nomeapp: tools.getNomeAppByIdApp(idapp),
user: user,
name: user.name,
username: user.username,
surname: user.surname,
strlinksetpassword: this.getlinkRequestNewPassword(idapp, emailto, tokenforgot),
emailto: emailto,
};
this.sendEmail_base('resetpwd/' + lang, emailto, mylocalsconf, '');
},
sendEmail_Booking: async function (res, lang, emailto, user, idapp, recbooking) {
tools.mylog('sendEmail_Booking');
tools.mylog('tools.getNomeAppByIdApp(idapp)', tools.getNomeAppByIdApp(idapp), idapp);
mylocalsconf = {
idapp,
dataemail: await this.getdataemail(idapp),
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() + ' ' + tools.getres__('partecipanti', res);
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 + '/' + tools.LANGADMIN, tools.getAdminEmailByIdApp(idapp), mylocalsconf, '');
if (tools.isManagAndAdminDifferent(idapp)) {
this.sendEmail_base('admin/' + texthtml + '/' + tools.LANGADMIN, tools.getManagerEmailByIdApp(idapp), mylocalsconf, '');
}
}));
},
sendEmail_CancelBooking: async function (res, lang, emailto, user, idapp, recbooking) {
tools.mylog('sendEmail_CancelBooking');
mylocalsconf = {
idapp,
dataemail: await this.getdataemail(idapp),
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() + ' ' + tools.getres__('partecipanti', res);
this.sendEmail_base('booking/cancelbooking/' + lang, emailto, mylocalsconf, tools.getreplyToEmailByIdApp(idapp));
// Send Email also to the Admin
this.sendEmail_base('admin/cancelbooking/' + tools.LANGADMIN, tools.getAdminEmailByIdApp(idapp), mylocalsconf, '');
if (tools.isManagAndAdminDifferent(idapp)) {
this.sendEmail_base('admin/cancelbooking/' + tools.LANGADMIN, tools.getManagerEmailByIdApp(idapp), mylocalsconf, '');
}
},
sendEmail_Msg: async function (res, lang, emailto, user, idapp, recmsg) {
tools.mylog('sendEmail_Msg');
tools.mylog('tools.getNomeAppByIdApp(idapp)', tools.getNomeAppByIdApp(idapp), idapp);
mylocalsconf = {
idapp,
dataemail: await this.getdataemail(idapp),
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);
},
Add_to_MailingList_AndSendEmailNotify: async function (lang, user, idapp, sendnews) {
// console.log('idapp', idapp, tools.getNomeAppByIdApp(idapp));
mylocalsconf = {
idapp,
dataemail: await this.getdataemail(idapp),
locale: lang,
nomeapp: tools.getNomeAppByIdApp(idapp),
name: user.name,
surname: user.surname,
emailto: user.email,
};
const hash = tools.getHash(mylocalsconf.emailto);
// Check if exist to the Mailing List
let myperson = await MailingList.findByHash(idapp, hash);
if (!myperson || !myperson.statesub || !myperson.wrongerr) {
if (!myperson) {
myperson = new MailingList({
name: mylocalsconf.name,
surname: mylocalsconf.surname,
email: mylocalsconf.emailto,
hash
});
myperson._id = new ObjectID();
} else {
myperson.name = mylocalsconf.name;
myperson.surname = mylocalsconf.surname;
//myperson.email = mylocalsconf.emailto;
//myperson.hash = hash;
}
myperson.idapp = idapp;
myperson.statesub = true; // subscription
myperson.wrongerr = false;
// Add/save new record to the DB MailingList
const res = await myperson.save();
if (sendnews) {
// Send to the Admin an Email
this.sendEmail_base('admin/added_to_newsletter/' + tools.LANGADMIN, tools.getAdminEmailByIdApp(idapp), mylocalsconf, '');
if (tools.isManagAndAdminDifferent(idapp)) {
this.sendEmail_base('admin/added_to_newsletter/' + tools.LANGADMIN, tools.getManagerEmailByIdApp(idapp), mylocalsconf, '');
}
}
return { code: server_constants.RIS_SUBSCRIBED_OK, msg: server_constants.RIS_SUBSCRIBED_MSG[lang] }
} else {
// Already Esist
return {
code: server_constants.RIS_SUBSCRIBED_ALREADYEXIST,
msg: server_constants.RIS_SUBSCRIBED_MSG_ALREADYEXIST[lang]
}
}
},
Remove_from_MailingList: async function (lang, hashemail, idapp) {
// console.log('idapp', idapp, tools.getNomeAppByIdApp(idapp));
// Check if exist to the Mailing List
if (await MailingList.isUnsubscribed(idapp, hashemail)) {
return {
myperson: null,
code: server_constants.RIS_UNSUBSCRIBED_ALREADY_DONE,
msg: server_constants.RIS_UNSUBSCRIBED_MSG_ALREADY_DONE[lang]
}
}
const fields_to_update = {
statesub: false
};
let myperson = await MailingList.findOneAndUpdate({
idapp,
hash: hashemail
}, { $set: fields_to_update }, { new: false });
if (myperson) {
return { myperson, code: server_constants.RIS_UNSUBSCRIBED_OK, msg: '' }
} else {
// Not found !
return {
myperson: null,
code: server_constants.RIS_UNSUBSCRIBED_NOT_EXIST,
msg: server_constants.RIS_UNSUBSTR_NOT_EXIST[lang]
}
}
},
fieldsloop: function (mylocalsconf, myvar) {
const baseurl = tools.getHostByIdApp(mylocalsconf.idapp);
const urlunsibscribe = baseurl + '/unsubscribe?em=' + mylocalsconf.hashemail + '&mc=' + mylocalsconf.dataemail.mailchimpactive + '&email=' + mylocalsconf.emailto;
out = myvar.replace('{urlunsubscribe}', urlunsibscribe);
out = out.replace('{email}', mylocalsconf.emailto);
out = out.replace('{name}', mylocalsconf.name);
out = out.replace('{surname}', mylocalsconf.surname);
return out
},
replacefields: function (mylocalsconf) {
mylocalsconf.dataemail.disclaimer_out = this.fieldsloop(mylocalsconf, mylocalsconf.dataemail.disclaimer);
mylocalsconf.dataemail.disc_bottom_out = this.fieldsloop(mylocalsconf, mylocalsconf.dataemail.disc_bottom);
mylocalsconf.dataemail.templ.testoheadermail_out = this.fieldsloop(mylocalsconf, mylocalsconf.dataemail.templ.testoheadermail);
return mylocalsconf
},
getdataemail: async (idapp) => {
// console.log('getdataemail');
const mydata = {
content_after_events: await Settings.getValDbSettings(idapp, 'TEXT_AFTER_EV'),
mailchimpactive: tools.BoolToInt(await Settings.getValDbSettings(idapp, 'MAILCHIMP_ON')),
urltwitter: await Settings.getValDbSettings(idapp, 'URL_TWITTER'),
urlfb: await Settings.getValDbSettings(idapp, 'URL_FACEBOOK'),
urlyoutube: await Settings.getValDbSettings(idapp, 'URL_YOUTUBE'),
urlinstagram: await Settings.getValDbSettings(idapp, 'URL_INSTAGRAM'),
textpromo: await Settings.getValDbSettings(idapp, 'TEXT_PROMO'),
disclaimer: await Settings.getValDbSettings(idapp, 'TEXT_DISCLAIMER'),
disc_bottom: await Settings.getValDbSettings(idapp, 'TEXT_DISC_BOTTOM'),
firma: await Settings.getValDbSettings(idapp, 'TEXT_SIGN'),
arrdiscipline: await Discipline.getDisciplineforNewsletter(idapp),
disc_title: await Settings.getValDbSettings(idapp, 'DISC_TITLE'),
height_logo: await Settings.getValDbSettings(idapp, 'HEIGHT_LOGO'),
from: await Settings.getValDbSettings(idapp, 'EMAIL_FROM'),
email_reply: await Settings.getValDbSettings(idapp, 'EMAIL_REPLY', ''),
pwd_from: await Settings.getValDbSettings(idapp, 'PWD_FROM'),
email_service: await Settings.getValDbSettings(idapp, 'EMAIL_SERVICE_SEND'),
email_port: await Settings.getValDbSettings(idapp, 'EMAIL_PORT'),
templemail_id: await Settings.getValDbSettings(idapp, 'TEMPLEMAIL_ID'),
};
// console.log(mydata.templemail_id);
mydata.templ = await TemplEmail.findOne({_id: mydata.templemail_id });
// console.log(mydata.templ);
return mydata
},
getTransport: (mylocalsconf) => {
// Create Transport
let smtpTransport = null;
if (mylocalsconf.dataemail.email_service !== 'gmail' && mylocalsconf.dataemail.email_service !== undefined) {
smtpTransport = nodemailer.createTransport({
host: mylocalsconf.dataemail.email_service,
port: mylocalsconf.dataemail.email_port,
auth: {
user: mylocalsconf.dataemail.from,
pass: mylocalsconf.dataemail.pwd_from
}
});
} else if (mylocalsconf.dataemail.email_service === 'gmail' && mylocalsconf.dataemail.email_service !== undefined) {
smtpTransport = {
service: 'gmail', //'Gmail',
auth: {
user: mylocalsconf.dataemail.from,
pass: mylocalsconf.dataemail.pwd_from
}
};
} else {
smtpTransport = {
service: 'gmail',
auth: {
user: tools.getEmailByIdApp(mylocalsconf.idapp),
pass: tools.getPwdByIdApp(mylocalsconf.idapp)
}
};
}
return smtpTransport;
},
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.findAllIdAppSubscribed(idapp);
const myarrevents = await MyEvent.getLastEvents(idapp);
mylocalsconf = {
idapp,
locale: lang,
nomeapp: tools.getNomeAppByIdApp(idapp),
arrevents: myarrevents,
baseurl: tools.getHostByIdApp(idapp),
dataemail: await this.getdataemail(idapp)
};
await Newstosent.processingJob(id_newstosent, true);
const mynewsrec = await Newstosent.findOne({ _id: id_newstosent });
mynewsrec.numemail_tot = userstosend.length;
mynewsrec.templemail_str = mylocalsconf.dataemail.templ.subject;
mynewsrec.numemail_sent = await MailingList.getnumSent(idapp, id_newstosent);
const smtpTransport = this.getTransport(mylocalsconf);
// LOOP USERS EMAIL
for (const user of userstosend) {
const isok = await MailingList.isOk(idapp, user._id, id_newstosent);
if (isok) {
let secpause = await Settings.getValDbSettings(idapp, 'MSEC_PAUSE_SEND', process.env.DELAY_SENDEMAIL);
if (secpause < process.env.DELAY_SENDEMAIL)
secpause = process.env.DELAY_SENDEMAIL;
activate = await Newstosent.isActivated(id_newstosent);
if (!activate) {
// Invio Newsletter Abortito!
mynewsrec.error_job = 'Invio Newsletter abortito alle ore ' + new Date().toDateString() + new Date().toTimeString();
await mynewsrec.save();
await Newstosent.processingJob(id_newstosent, false);
console.log('*** L\'Invio della Newsletter è stato fermato ! ');
return false
}
mylocalsconf.name = user.name;
mylocalsconf.surname = user.surname;
mylocalsconf.emailto = user.email;
mylocalsconf.hashemail = tools.getHash(user.email);
mylocalsconf = this.replacefields(mylocalsconf);
// If has already sent, don't send it again!
if (user.lastid_newstosent !== id_newstosent.toString()) {
console.log('@@@@@ COMPARE DIVERSI: lastid', user.lastid_newstosent, 'idsent', id_newstosent.toString());
if (process.env.DEBUG)
await tools.snooze(5000);
// Send Email to the User
// console.log('-> Invio Email (', mynewsrec.numemail_sent, '/', mynewsrec.numemail_tot, ')');
const esito = this.sendEmail_base('newsletter/' + lang, mylocalsconf.emailto, mylocalsconf, mylocalsconf.dataemail.email_reply, smtpTransport);
//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 });
//Delay for send email...
await tools.snooze(secpause);
mynewsrec.lastemailsent_Job = new Date();
mynewsrec.numemail_sent = await MailingList.getnumSent(idapp, id_newstosent);
const recsaved = await mynewsrec.save();
} else {
console.log('*** COMPARE: UGUALI !!!!! lastid', user.lastid_newstosent, 'idsent', id_newstosent.toString());
}
}
}
await Newstosent.endJob(id_newstosent);
await Newstosent.processingJob(id_newstosent, false);
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) {
if (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, previewonly) {
const myarrevents = await MyEvent.getLastEvents(idapp);
const myemail = await Settings.getValDbSettings(idapp, 'EMAIL_TEST');
mylocalsconf = {
idapp,
locale: lang,
nomeapp: tools.getNomeAppByIdApp(idapp),
arrevents: myarrevents,
name: 'TestNome',
surname: 'TestCognome',
emailto: myemail,
baseurl: tools.getHostByIdApp(idapp),
hashemail: tools.getHash(myemail),
};
console.log('myarrevents');
console.table(mylocalsconf.arrevents);
mylocalsconf.dataemail = await this.getdataemail(idapp);
this.replacefields(mylocalsconf);
const smtpTransport = this.getTransport(mylocalsconf);
console.log('-> Invio Email TEST a', mylocalsconf.emailto, 'previewonly', previewonly);
return this.sendEmail_base('newsletter/' + lang, mylocalsconf.emailto, mylocalsconf, '', smtpTransport, previewonly);
}
}
;