Search code examples
javascriptnode.jsmandrill

How to send mandrill emails to array of emails?


I'm building an app in Node and I'm using mandrill to send emails every time there is a new user to a predefined array of emails. I have an array of emails:

And I have this function where

newUserEmail(user_name, email) {
  emailArray = [[email protected], [email protected], [email protected]]
  const message = {
    html: '<p>Name: *|NAME|* <br> Email: *|EMAIL|*</p>',
    text: 'Name: *|NAME|*, Email: *|EMAIL|*',
    subject: 'New person arrived',
    from_email: '[email protected]',
    from_name: 'New',
    to: [{
      email: emailArray,
      type: 'to'
    }],
    merge: true,
    merge_vars: [{
      rcpt: emailArray,
      vars: [{
        name: 'NAME',
        content: user_name
      }, {
        email: 'EMAIL',
        content: email
      }]
    }]
  };
  mandrill_client.messages.send({ message }, function(result) {
    console.log(result);
  }, function(e) {
    console.log(`A mandrill error occurred: ${e.name} - ${e.message}`);
  });
}

I get this on my console:

[ { email: 'Array',
    status: 'invalid',
    _id: '...',
    reject_reason: null } ]

If I set only one email, it gets sent without problems.

Do I need to make a loop and run this function as many times as there are emails in the array? I hoped mandrill would recognise emails in the array :(


Solution

  • From what I gathered after a look at the documentation it looks like each object in the "to" array is an individual email address.

    I would not run the function for each email address. Just map over the email array. For example:

    const formattedArray = emailArray.map(email => ({ email, type: 'to' }));
    
    // if you're not a fan of arrow functions
    
    const formattedArray = emailArray.map(function(email) {
       return { email, type: 'to' };
    });
    

    Then in the mandrill message you can just set "to" equal to the formattedArray

    to: formattedArray