Advertisement
Guest User

Untitled

a guest
Mar 1st, 2017
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1. // Подключение:
  2. // mail = require('modules/mail').mail,
  3. //-------------------------------------------
  4. // Использование:
  5. // mail(subject, mess, recipient, sender);
  6. //-------------------------------------------
  7. // Отправляем письмо на почту recipient от отправителя sender
  8. // Если recipient не указан, отправляем письмо на почту, указанную в config
  9. //-------------------------------------------
  10.  
  11. const config = require('config'),
  12. nodemailer = require('nodemailer'),
  13. log = require('libs/log')(module),
  14. db = require('modules/db-find'),
  15. validator = require('validator'),
  16. SystemError = require('error/system').SystemError;
  17.  
  18.  
  19.  
  20. function SendMail(subject, message, recipient = "", sender = "", emailLogin = "", emailPass = "") {
  21.  
  22. // Достаем тип почты (gmail, yandex...)
  23. let emailType = config.get('email-login').split('@')[1].split('.')[0];
  24.  
  25. // Проверяем, есть ли логин и пароль от почты
  26. let transporter = nodemailer.createTransport({
  27. service: emailType,
  28. auth: {
  29. user: emailLogin || config.get('email-login'),
  30. pass: emailPass || config.get('email-pass')
  31. }
  32. });
  33.  
  34. // Если нет отправителя и получателя, то письмо отправляется само себе
  35. let mailOptions = {
  36. from: validator.isEmail(sender) || validator.isEmail(emailLogin) || config.get('email-login'),
  37. to: validator.isEmail(recipient) || validator.isEmail(emailLogin) || config.get('email-login'),
  38. subject: subject || 'Без темы',
  39. text: message || 'Нет сообщения'
  40. };
  41.  
  42. transporter.sendMail(mailOptions, (err, info) => {
  43. if (err) { return new SystemError(500, err); }
  44. log.info('Message sent by email');
  45. });
  46. }
  47.  
  48.  
  49.  
  50. function mail(subject, message, recipient, sender) {
  51. (async () => {
  52. // Достаем логин и пароль от почты
  53. let getBase = async () => { return await db.findOne('Setting'); };
  54. let base = await getBase();
  55.  
  56. // Если базы нет, то будем использовать значения из конфига
  57. if (base) {
  58. new SendMail(subject, message, recipient, sender, base.emailLogin, base.emailPass);
  59. } else {
  60. new SendMail(subject, message, recipient, sender);
  61. }
  62.  
  63. })().catch((err)=> {
  64. if (err) { return new SystemError(500, err); }
  65. });
  66.  
  67. }
  68.  
  69.  
  70.  
  71. exports.mail = mail;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement