9

I am using drupal_mail to send email,

$to = 'email@email.com';
drupal_mail('$module_name', $key, $to, language_default(), $params = array('username' => 'Tanvir'), $from = NULL, $send = TRUE);

I want to send email to multiple email addresses at once. Should I be doing this?

$to  = array('one@email.com', 'two@email.com', 'three@email.com',);
drupal_mail('$module_name', $key, $to, language_default(), $params = array('username' => 'Tanvir'), $from = NULL, $send = TRUE);

4 Answers 正确答案 

26

The to-parameter to drupal_mail is a string, not an array. But you can have as many receipent as you like in the the e-mails "to" string, provided they're separated by commas.

So to send the same mail to multiple recipients, do the following:

$to  = 'one@email.com,two@email.com,three@email.com';
drupal_mail('$module_name', $key, $to, language_default(), $params = array('username' => 'Tanvir'), $from = NULL, $send = TRUE);

Se also API documentation for drupal_mail

  • i only say that when i try $to  = 'one@email.com, two@email.com, three@email.com'; I receive only one email, but when I try $to  = 'one@email.com,two@email.com,three@email.com'; without spaces I received all emails! 
    – Michael
     Feb 28, 2017 at 10:06
1

Use hook_mail to send multiple receipients by passing:

$params = array();
$params['cc'][] = 'abc@ex.org'
drupal_mail('$module_name', 'custom_key', $to, language_default(), $params = array('username' => 'Tanvir'), $from = NULL, $send = TRUE);


//hook will be the module name

function hook_mail($key,&$message,$params) {

  if ($key == 'custom_key') {
    $message['headers']['cc'] = $params['cc'];
    //.
    //.
    //.
    //.
  }    
}
1

According to PHP doc you can send only one letter via one call of function drupal_mail. So, you should use cycle. Example

$to  = array('one@email.com', 'two@email.com', 'three@email.com',);
foreach ($to as $email) {
  drupal_mail('$module_name', $key, $email, language_default(), $params = array('username' => 'Tanvir'), $from = NULL, $send = TRUE);
}
0

If you read drupal_mail function documentation then you'd see '$to' param accepts string not an array in certain formats like:

  1. user@example.com

  2. user@example.com, anotheruser@example.com

  3. User

  4. User , Another User

So, we can easily convert your $to array into required format using implode function and hence you'll be to send email to multiple recipients in one go. Here's the code:

$to  = array('one@email.com', 'two@email.com', 'three@email.com',);

//To change array('one@email.com', 'two@email.com', 'three@email.com',)  -> 'one@email.com, two@email.com, three@email.com' use implode

$to_str = implode(",", $to);

drupal_mail('$module_name', $key, $to_str, language_default(), $params = array('username' => 'Tanvir'), $from = NULL, $send = TRUE);

Your Answer


来自  https://drupal.stackexchange.com/questions/116469/how-to-send-email-to-multiple-recipients-using-drupal-mail