循环通过所有用户发送电子邮件Node JS

时间:2018-03-07 12:47:44

标签: javascript node.js mongodb express mailgun

我试着找到答案但不能。我是Node Js的新手,拥有包含用户电子邮件的用户架构。我希望有一个包含“主题”和“消息”字段的表单,以及一个提交按钮,该按钮随后会在电子邮件中发送表单的内容。我目前正在使用Mailgun,标准电子邮件如下所示:

 var data = {
            to: user.email,
            from: '"Lighthouse Studios" <noreply@reception.lighthousespace.co.uk>',
            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>

总而言之,我想在单击“提交”按钮时使用该表单向所有用户发送电子邮件。感谢您抽出宝贵时间阅读本文。

1 个答案:

答案 0 :(得分:0)

 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" <noreply@reception.lighthousespace.co.uk>',
                        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);
                });
           }   
        })

希望这个会起作用