Цикл через всех пользователей для отправки электронной почты Node JS

Я пытался найти ответ, но не смог. Я новичок в Node Js, и у меня есть схема пользователя, которая включает электронные письма пользователей. Я хочу иметь форму с полями «тема» и «сообщение», а также кнопку отправки, которая затем отправляла бы содержимое формы по электронной почте. В настоящее время я использую Mailgun, и стандартная электронная почта выглядит так:

 var data = {
            to: user.email,
            from: '"Lighthouse Studios" <[email protected]>',
            subject: 'Your password has been changed',
            text: 'Hello,\n\n' +
              'This is a confirmation that the password for your account ' + user.email + ' has just been changed.\n'
          };
          mailgun.messages().send(data, function (error, body) {
      console.log(body);
    });

И моя пользовательская схема выглядит так:

var UserSchema = new mongoose.Schema({
    username: {type: String, unique: true, required: true},
    name: {type: String, required: true},
    email: {type: String, unique: true, required: true},
    password: String,
    studio: {type: String, required: true},
    resetPasswordToken: String,
    resetPasswordExpires: Date,

    comments: [
      {
            quantity: String,
            received: { type: Date, default: Date.now },
            collected: { type: String, default: "At Reception" }
      }
   ],

    isAdmin: {type: Boolean, default: false}
});

Вот код формы:

<form action="/" method="POST">
            <div class="form-group">
                <input class="form-control" type="text" name="subject" placeholder="Subject">
            </div>
            <div class="form-group">
               <textarea class="form-control" rows="5" id="comment" name="message" placeholder="Message"></textarea>
            </div>
            <div class="form-group">
                <input class="btn btn-lg btn-primary btn-block" type="submit" value="Send">
            </div>

        </form>

Подводя итог, я хочу использовать форму для отправки всем пользователям электронных писем при нажатии кнопки «Отправить». Спасибо, что уделили время, прочитав это.


person Adam Furniss    schedule 07.03.2018    source источник


Ответы (1)


 UserModel.find({})
         .select('email')
         .lean()
         .exec((err,users)=>{
            if(users){
              let userEmails = "";
              let recp = users.reduce((a,u)=>{ a[u.email]={}; a[u.email].email = u.email; userEmails+=u.email; return a; },{})
              let data = {
                        to: userEmails,
                        from: '"Lighthouse Studios" <[email protected]>',
                        subject: 'Your password has been changed',
                         text: 'Hello,\n\n' +'This is a confirmation that the password for your account ' + %recipient.email% + ' has just been changed.\n',
                        'recipient-variables': JSON.stringify(recp)
                };

                mailgun.messages().send(data, function (error, body) {
                console.log(body);
                });
           }   
        })

Надеюсь, это сработает

person Saikat Hajra    schedule 07.03.2018