{"size": 1453, "ext": "js", "max_stars_repo_path": "server/lib/emails/transporter.js", "max_stars_repo_name": "lnceballosz/inventaire", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "server/lib/emails/transporter.js", "max_issues_repo_name": "lnceballosz/inventaire", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "server/lib/emails/transporter.js", "max_forks_repo_name": "lnceballosz/inventaire", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 28.4901960784, "max_line_length": 80, "alphanum_fraction": 0.6978664831}
// SPDX-FileCopyrightText:  2014  Maxime Lathuilière, Vincent Jumeaux
// SPDX-License-Identifier: AGPL-3.0-only

const CONFIG = require('config')
const __ = CONFIG.universalPath
const _ = require('builders/utils')

const nodemailer = require('nodemailer')
const hbs = require('nodemailer-express-handlebars')
const handlebarsHelpers = require('./handlebars_helpers')
const viewsPath = __.path('lib', 'emails/views')

const options = {
  viewEngine: {
    extname: '.hbs',
    layoutsDir: `${viewsPath}/layouts/`,
    defaultLayout: 'template',
    partialsDir: `${viewsPath}/partials/`,
    helpers: handlebarsHelpers
  },
  viewPath: viewsPath,
  extName: '.hbs'
}

const { defaultFrom, preview } = CONFIG.mailer
const defaults =
  { from: defaultFrom }

const transporter = nodemailer.createTransport(CONFIG.mailer, defaults)

if (preview) {
  // overriding Nodemailer::sendMail to generate a preview file
  // instead of sending the email
  const sendMail = require('./preview_email')
  transporter.sendMail = sendMail.bind(transporter)
}

transporter.use('compile', hbs(options))

module.exports = {
  sendMail: async email => {
    const { template, subject } = email
    return transporter.sendMail(email)
    .then(_.Success(`email sent (template="${template}" subject="${subject}")`))
    .catch(err => {
      _.error(err, `email error (template="${template}" subject="${subject}")`)
      return _.warn(email, 'associated email')
    })
  }
}
