Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import path from 'path';
- import nodemailer from 'nodemailer';
- import { htmlToText } from 'nodemailer-html-to-text';
- import templates from '../templates';
- import projectInfo from '../../project-info';
- import logger from '../../logger';
- const moduleLogger = logger.child({
- module: 'emailServiceActions'
- });
- const packageInfo = require('../../../package.json');
- // Get service options
- const emailOptions = projectInfo['email'] || {};
- const emailService = process.env['EMAIL_SERVICE'] || emailOptions['service'];
- const emailHost = process.env['EMAIL_HOST'] || emailOptions['host'];
- const emailPort = process.env['EMAIL_HORT'] || emailOptions['port'];
- const emailUser = process.env['EMAIL_USER'] || emailOptions['user'];
- const emailPassword = process.env['EMAIL_PASS'] || emailOptions['pass'];
- const transportOptions = {};
- if (emailService) {
- transportOptions.service = emailService;
- }
- if (emailHost) {
- transportOptions.host = emailHost;
- }
- if (emailPort) {
- transportOptions.port = emailPort;
- }
- if (emailUser) {
- transportOptions.auth = {
- user: emailUser,
- pass: emailPassword || ''
- };
- }
- // Get e-mail configuration
- const emailSettings = projectInfo['email'];
- const config = {...emailSettings};
- if (process.env['EMAIL_FROM']) {
- config['from'] = process.env['EMAIL_FROM'];
- }
- config['recipients'] = config['recipients'] || {};
- // Create nodemailer transporter
- const transporter = nodemailer.createTransport(transportOptions);
- transporter.use('compile', htmlToText());
- export default {
- config,
- /**
- * @param {Object} params
- * @param {String} [params.to]
- * @param {String} [params.subject]
- * @param {String} [params.html]
- * @param {String} [params.text]
- */
- send: function (params) {
- const defaultConfig = this.config;
- const finalParams = {...defaultConfig, ...params};
- moduleLogger.trace('send', finalParams);
- transporter.sendMail(finalParams, (error, info) => {
- if (error) {
- return moduleLogger.error(error);
- }
- });
- },
- /**
- * @param {String} name of template file in email directory
- * @param {Object|String} params for send() or just subject
- * @param {Object} values to apply for the template
- */
- sendTemplate: function (name, params, values) {
- const templateName = path.join('email', name);
- const self = this;
- moduleLogger.trace('sendTemplate');
- templates.render(templateName, values, {
- cache: false
- }).then((html) => {
- moduleLogger.trace('sendTemplate: rendered to ', html);
- let finalParams;
- if (typeof params === 'string') {
- finalParams = {subject: params};
- } else {
- finalParams = params;
- }
- finalParams.html = html;
- self.send(finalParams);
- }).catch((err) => {
- moduleLogger.error('sendTemplate', { arguments, err });
- });
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement