Skip to content
Snippets Groups Projects
Commit ad988465 authored by Aditya Ghag's avatar Aditya Ghag
Browse files

smtpchanges

parent 71de6abe
No related branches found
No related tags found
2 merge requests!1Validating email functionality,!2Validating email functionality
# sendgrid test # sendgrid test
# SENDGRID_API_KEY = SMTP_HOST=
SMTP_PORT=
SMTP_USER=
SMTP_PASS=
# gwdg email server # gwdg email server
SMTP_HOST=mailer.gwdg.de # email.gwdg.de does not work when called on the server. SMTP_HOST=mailer.gwdg.de # email.gwdg.de does not work when called on the server.
......
/** /**
* @module email * @module email
*/ */
require('dotenv').config(); require('dotenv').config()
const nodemailer = require('nodemailer'); const nodemailer = require('nodemailer')
const moment = require('moment'); const moment = require('moment')
const fs = require('fs'); const fs = require('fs')
const path = require('path'); const path = require('path')
const HTML_TEMPLATE = fs.readFileSync(path.resolve(__dirname, './email-template.html'), 'utf-8'); const HTML_TEMPLATE = fs.readFileSync(
const logger = require('./logger'); path.resolve(__dirname, './email-template.html'),
'utf-8',
)
const logger = require('./logger')
// to send the email using sendgrid service // to send the email using sendgrid service
const sgMail = require('@sendgrid/mail') const sgMail = require('@sendgrid/mail')
sgMail.setApiKey(process.env.SENDGRID_API_KEY) sgMail.setApiKey(process.env.SENDGRID_API_KEY)
// testing with nodemailer
const transport = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: process.env.SMTP_PASS,
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASS,
},
})
/** /**
* @function sendNoticeEmails to send each received offline validator contact an email. * @function sendNoticeEmails to send each received offline validator contact an email.
* *
* Takes an array of contacts and wraps each of them in a Promise that resolves into the response of the function transport.sendMail() * Takes an array of contacts and wraps each of them in a Promise that resolves into the response of the function transport.sendMail()
* *
* @param {Array<Object>} contactsArray from module contacts.js function getContactDetails * @param {Array<Object>} contactsArray from module contacts.js function getContactDetails
* @returns {Promise} initially a single wrapped promise, returns an array of results. see Promise.all(). * @returns {Promise} initially a single wrapped promise, returns an array of results. see Promise.all().
*/ */
exports.sendNoticeEmails = (contactsArray, ccContacts) => { exports.sendNoticeEmails = (contactsArray, ccContacts) => {
let promises = []; let promises = []
for (let i = 0; i < contactsArray.length; i++) { for (let i = 0; i < contactsArray.length; i++) {
promises.push( promises.push(
later(3000 * i) // Avoid sending too much at once later(3000 * i) // Avoid sending too much at once
.then(() => sendNoticeEmail(contactsArray[i], ccContacts)) .then(() => sendNoticeEmail(contactsArray[i], ccContacts)),
) )
} }
return Promise.all(promises); return Promise.all(promises)
} }
function later(delay) { function later(delay) {
return new Promise(function (resolve) { return new Promise(function (resolve) {
setTimeout(resolve, delay); setTimeout(resolve, delay)
}); })
} }
/** /**
* Function to send error emails to admins when the script fails. * Function to send error emails to admins when the script fails.
* *
* @param {Array} emails - array of email strings as receivers * @param {Array} emails - array of email strings as receivers
* @param {Error} error - the thrown Error object * @param {Error} error - the thrown Error object
*/ */
...@@ -52,16 +65,16 @@ exports.sendErrorEmails = (emails, error) => { ...@@ -52,16 +65,16 @@ exports.sendErrorEmails = (emails, error) => {
subject: '❗ ERROR: bloxberg Validator Offline', subject: '❗ ERROR: bloxberg Validator Offline',
text: `When running the script the following error is encountered\n\n text: `When running the script the following error is encountered\n\n
${error.message}\n\n ${error.message}\n\n
${error.stack}` ${error.stack}`,
}; }
// return setTimeout(() => Promise.resolve(`Email sent to ${institution}: ${email}`), Math.random() * 1000 * 2) // Debug with randomly resolved Promises. // return setTimeout(() => Promise.resolve(`Email sent to ${institution}: ${email}`), Math.random() * 1000 * 2) // Debug with randomly resolved Promises.
return sgMail.send(message); return sgMail.send(message)
} }
/** /**
* Function to send error emails to bloxberg admins when the script fails. * Function to send error emails to bloxberg admins when the script fails.
* *
* @param {Array} emails - array of email strings as receivers * @param {Array} emails - array of email strings as receivers
* @param {Array} notFoundContacts - array of validator objects without a found contact. * @param {Array} notFoundContacts - array of validator objects without a found contact.
* @example * @example
...@@ -71,26 +84,32 @@ exports.sendErrorEmails = (emails, error) => { ...@@ -71,26 +84,32 @@ exports.sendErrorEmails = (emails, error) => {
* ] * ]
*/ */
exports.sendNotFoundEmails = (notFoundContacts, admins) => { exports.sendNotFoundEmails = (notFoundContacts, admins) => {
if (notFoundContacts.length < 1) if (notFoundContacts.length < 1) return Promise.resolve()
return Promise.resolve(); logger.log(
logger.log('Sending not found emails to ' + emails.join() + ' for the addresses: ' + notFoundContacts.map(contact => contact.address).join()) 'Sending not found emails to ' +
emails.join() +
' for the addresses: ' +
notFoundContacts.map((contact) => contact.address).join(),
)
const message = { const message = {
from: `monitoring@bloxberg.org`, from: `monitoring@bloxberg.org`,
to: admins, to: admins,
subject: '❗ Contact Not Found: bloxberg Validator Offline', subject: '❗ Contact Not Found: bloxberg Validator Offline',
text: `The following validators do not have an assigned contact and text:
`The following validators do not have an assigned contact and
hence were not able to be contacted. If the institution name is undefined, hence were not able to be contacted. If the institution name is undefined,
it means an associated institution for the address couldn't be found in Cobra input. it means an associated institution for the address couldn't be found in Cobra input.
Otherwise the institution has an associated address but is missing any contacts. \n\n` + Otherwise the institution has an associated address but is missing any contacts. \n\n` +
notFoundContacts.map(contact => { notFoundContacts
return `Institution: ${contact.institution} \n\n .map((contact) => {
return `Institution: ${contact.institution} \n\n
Address: ${contact.address}\n\n` Address: ${contact.address}\n\n`
}).join() })
.join(),
}; }
// return setTimeout(() => Promise.resolve(`Email sent to ${institution}: ${email}`), Math.random() * 1000 * 2) // Debug with randomly resolved Promises. // return setTimeout(() => Promise.resolve(`Email sent to ${institution}: ${email}`), Math.random() * 1000 * 2) // Debug with randomly resolved Promises.
return sgMail.send(message); return sgMail.send(message)
} }
/** /**
...@@ -129,45 +148,49 @@ exports.sendNotFoundEmails = (notFoundContacts, admins) => { ...@@ -129,45 +148,49 @@ exports.sendNotFoundEmails = (notFoundContacts, admins) => {
*/ */
function sendNoticeEmail(contactArray, ccContacts) { function sendNoticeEmail(contactArray, ccContacts) {
logger.log('Sending notice email to: ', contactArray) logger.log('Sending notice email to: ', contactArray)
let { institution, address, lastOnline } = contactArray[0]; // Same for all contacts let { institution, address, lastOnline } = contactArray[0] // Same for all contacts
let fullNames = '', emails = [] // Different if multiple contacts let fullNames = '',
emails = [] // Different if multiple contacts
for (contact of contactArray) { for (contact of contactArray) {
let { academicTitle, firstName, lastName, email } = contact; let { academicTitle, firstName, lastName, email } = contact
fullNames += (academicTitle ? ' ' + academicTitle : '') + ` ${firstName} ${lastName}, `; // use academic title if exist fullNames +=
emails.push(email); (academicTitle ? ' ' + academicTitle : '') + ` ${firstName} ${lastName}, ` // use academic title if exist
emails.push(email)
} }
let lastOnlineDateString = moment(lastOnline).format('MMMM Do YYYY') let lastOnlineDateString = moment(lastOnline).format('MMMM Do YYYY')
let lastOnlineTimeString = moment(lastOnline).format('hh:mm a [Germany time]') // moment uses server's local time. Our servers are in Germany. let lastOnlineTimeString = moment(lastOnline).format('hh:mm a [Germany time]') // moment uses server's local time. Our servers are in Germany.
const properties = { const properties = {
fullNames, institution, address, fullNames,
lastOnlineDateString, lastOnlineTimeString institution,
address,
lastOnlineDateString,
lastOnlineTimeString,
} }
const message = { const message = {
from: `monitoring@bloxberg.org`, from: `ghag@mpdl.mpg.de`,
to: emails, to: emails,
cc: ccContacts, cc: ccContacts,
subject: 'bloxberg Validator Offline', subject: 'bloxberg Validator Offline',
html: applyTemplate(HTML_TEMPLATE, properties) html: applyTemplate(HTML_TEMPLATE, properties),
}; }
console.log('message',message)
// return setTimeout(() => Promise.resolve(`Email sent to ${institution}: ${email}`), Math.random() * 1000 * 2) // Debug with randomly resolved Promises. // return setTimeout(() => Promise.resolve(`Email sent to ${institution}: ${email}`), Math.random() * 1000 * 2) // Debug with randomly resolved Promises.
return sgMail.send(message) return transport.sendMail(message)
} }
// Replaces properties in the template with {{ double parantheses }} with values in the parameter object. // Replaces properties in the template with {{ double parantheses }} with values in the parameter object.
// from: https://stackoverflow.com/questions/29831810/how-to-fill-information-into-a-template-text-file // from: https://stackoverflow.com/questions/29831810/how-to-fill-information-into-a-template-text-file
function applyTemplate(template, properties) { function applyTemplate(template, properties) {
var returnValue = ""; var returnValue = ''
var templateFragments = template.split("{{"); var templateFragments = template.split('{{')
returnValue += templateFragments[0]; returnValue += templateFragments[0]
for (var i = 1; i < templateFragments.length; i++) { for (var i = 1; i < templateFragments.length; i++) {
var fragmentSections = templateFragments[i].split("}}", 2); var fragmentSections = templateFragments[i].split('}}', 2)
returnValue += properties[fragmentSections[0]]; returnValue += properties[fragmentSections[0]]
returnValue += fragmentSections[1]; returnValue += fragmentSections[1]
} }
return returnValue; return returnValue
} }
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment