Created
March 2, 2017 01:52
-
-
Save Loiree/20d80999f5a57b60b15be7855d635b29 to your computer and use it in GitHub Desktop.
Отправка почты
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Подключение: | |
// mail = require('modules/mail').mail, | |
//------------------------------------------- | |
// Использование: | |
// mail(subject, mess, recipient, sender); | |
//------------------------------------------- | |
// Отправляем письмо на почту recipient от отправителя sender | |
// Если recipient не указан, отправляем письмо на почту, указанную в config | |
//------------------------------------------- | |
const config = require('config'), | |
nodemailer = require('nodemailer'), | |
log = require('libs/log')(module), | |
db = require('modules/db-find'), | |
validator = require('validator'), | |
SystemError = require('error/system').SystemError; | |
function SendMail(subject, message, recipient = "", sender = "", emailLogin = "", emailPass = "") { | |
// Достаем тип почты (gmail, yandex...) | |
let emailType = config.get('email-login').split('@')[1].split('.')[0]; | |
// Проверяем, есть ли логин и пароль от почты | |
let transporter = nodemailer.createTransport({ | |
service: emailType, | |
auth: { | |
user: emailLogin || config.get('email-login'), | |
pass: emailPass || config.get('email-pass') | |
} | |
}); | |
// Если нет отправителя и получателя, то письмо отправляется само себе | |
let mailOptions = { | |
from: validator.isEmail(sender) || validator.isEmail(emailLogin) || config.get('email-login'), | |
to: validator.isEmail(recipient) || validator.isEmail(emailLogin) || config.get('email-login'), | |
subject: subject || 'Без темы', | |
text: message || 'Нет сообщения' | |
}; | |
transporter.sendMail(mailOptions, (err, info) => { | |
if (err) { return new SystemError(500, err); } | |
log.info('Message sent by email'); | |
}); | |
} | |
function mail(subject, message, recipient, sender) { | |
(async () => { | |
// Достаем логин и пароль от почты | |
let getBase = async () => { return await db.findOne('Setting'); }; | |
let base = await getBase(); | |
// Если базы нет, то будем использовать значения из конфига | |
if (base) { | |
new SendMail(subject, message, recipient, sender, base.emailLogin, base.emailPass); | |
} else { | |
new SendMail(subject, message, recipient, sender); | |
} | |
})().catch((err)=> { | |
if (err) { return new SystemError(500, err); } | |
}); | |
} | |
exports.mail = mail; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment