Skip to content

Instantly share code, notes, and snippets.

@dkiyatkin

dkiyatkin/sendMail.js

Last active Sep 21, 2016
Embed
What would you like to do?
import fs from 'fs'
import p from 'path'
import mkdirp from 'mkdirp'
import Mustache from 'mustache'
import nodemailer from 'nodemailer'
const mailConfFile = './data/contactFormSendMail/mail.json'
const mailTplFile = './data/contactFormSendMail/mail.tpl'
const mailLogDir = './log/contactFormSendMail/'
function getMailCtx (req) {
const mailCtx = {} // составить конфиг
mailCtx.browser = req.headers['user-agent']
mailCtx.ip = req.ip // если nginx то app.enable('trust proxy') в server.js
mailCtx.date = new Date().toString()
mailCtx.message = req.body.message
mailCtx.email = req.body.email
mailCtx.name = req.body.name
return mailCtx
}
/**
* Получить настройки отправки сообщения
* @return {Promise}
*/
function getMailConf () {
return fs.readFileAsync(mailConfFile, 'utf8').then(function (content) {
return JSON.parse(content)
})
}
/**
* Загрузить и распарсить шаблон тела сообщения
* @arg {Object} mailCtx
* @return {Promise}
*/
function getMailBody (mailCtx) {
return fs.readFileAsync(mailTplFile, 'utf8').then(function (content) {
return Mustache.render(content, mailCtx)
})
}
/**
* Запись копии
* @arg {String} mailBody
* @return {Promise}
*/
function writeLog (mailBody) {
const logFile = p.join(mailLogDir, Math.round((new Date()).getTime()) + '.txt')
return fs.writeFileAsync(logFile, mailBody, 'utf8')
}
/**
* Получить текст письма, сделав лог копии сообщения
* @arg {Object} mailCtx
* @return {Promise.<Object>} mailBody
*/
function setMailBody (mailCtx) {
return Promise.all([
getMailBody(mailCtx),
mkdirp.mkdirpAsync(mailLogDir)
]).spread(function (mailBody) {
return writeLog(mailBody).then(function () {
return mailBody
})
})
}
/**
* Распарсить шаблон письма, сделать лог письма, загрузить системный конфиг и отправить
* @arg {Request} req
* @return {Promise}
*/
export default function sendEmail (req) {
const mailCtx = getMailCtx(req)
return Promise.all([getMailConf(), setMailBody(mailCtx)]).spread(function (mailConf, mailBody) {
const transporter = nodemailer.createTransport(mailConf.transport)
const mailOptions = {
replyTo: `${mailCtx.name} <${mailCtx.email}>`,
from: mailConf.from,
to: mailConf.to,
subject: mailConf.subject,
text: mailBody,
}
return transporter.sendMail(mailOptions)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.