const mailer = require('nodemailer');
const sys = require('../config/sys');

const mailrg = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
const transporter = mailer.createTransport({
  service: sys.mail.service,
  auth: {
    user: sys.mail.account,
    pass: sys.mail.pass
  }
});

/**
 * 邮件发送
 * @param {to, subject, html} receive 
 *      to string 接收者
 *      subject string 邮件标题
 *      html string 邮件内容
 * @return Pomise
 */
function send(receive) {
  return new Promise((resolve, reject) => {
    let {to, subject = '邮件发送', html} = receive;

    if (!mailrg.test(to)) {
      return reject('mail option to format Incorrect');
    } else if (!html || html.length === '') {
      return reject('mail option html format Incorrect');
    }

    transporter.sendMail({from: sys.mail.account, to, subject, html}, (err, info) => {
      if (err) {
        reject(err);
      } else {
        resolve(info);
      }
    });
  });
}

module.exports = exports = send;