2015-12-15 2 views
2

В настоящее время я работаю над базовой системой php mysql, которая отправит электронное письмо нескольким получателям из базы данных. Im уже выполняет поиск в форуме, и много ответов использует loop to email recipient. И затем я пытаюсь использовать цикл в получателе электронной почты, но просто могу отправить 1 письмо (хотя в базе данных есть 5 или более получателей электронной почты). Можете ли вы сказать мне, где мой код неправильный? Ниже мой код:Отправить письмо с базы данных с помощью phpmailer

function send_message($from, $to, $subject, $message_content) 
{ 
    require_once "function.php"; 
    require_once('phpmailer/PHPMailerAutoload.php'); 

    //Initiate the mailer class 
    $mail = new PHPMailer(); 

    //Check to see if SMTP creds have been defined 
    if(defined('SMTP_USER') && defined('SMTP_PASS') && defined('SMTP_LOCATION') && defined('SMTP_PORT')) 
    { 
     $mail->IsSMTP(); 
     $mail->Host = SMTP_LOCATION; 
     $mail->SMTPAuth = true; 
     $mail->Port = SMTP_PORT; 
     $mail->Username = SMTP_USER; 
     $mail->Password = SMTP_PASS; 

     if(defined('DEBUG') && DEBUG) 
     { 
      $mail->SMTPDebug = 1; 
     } 
    } 

    //Set the sender and receiver email addresses 

    $alamatmail=get_mail(); 
    foreach ($alamatmail as $datamail): 
     $from="[email protected]"; 
     $to=$datamail['email']; 
      //Include the phpmailer files 
      $mail->SetFrom($from, ""); 

      //We 'can' send to an array, in which case you'll want to explode at comma or line break 
      if(is_array($to)) 
      { 
       foreach($to as $i) 
       { 
        $mail->addAddress($i); 
       } 
      } 
      else 
      { 
       $mail->AddAddress($to, ""); 
      } 

      //Set the message subject 
      $mail->Subject = $subject; 

      //Add the message header 
      $message = file_get_contents('email-templates/email-header.php'); 

      //Add the message body 
      $message .= file_get_contents('email-templates/email-body.php'); 

      //Add the message footer content 
      $message .= file_get_contents('email-templates/email-footer.php'); 

      //Replace the codetags with the message contents 
      $replacements = array(
       '({message_subject})' => $subject, 
       '({message_body})' => nl2br(stripslashes($message_content)), 
      ); 
      $message = preg_replace(array_keys($replacements), array_values($replacements), $message); 

      //Make the generic plaintext separately due to lots of css and tables 
      $plaintext = $message_content; 
      $plaintext = strip_tags(stripslashes($plaintext), '<p><br><h2><h3><h1><h4>'); 
      $plaintext = str_replace(array('<p>', '<br />', '<br>', '<h1>', '<h2>', '<h3>', '<h4>'), PHP_EOL, $plaintext); 
      $plaintext = str_replace(array('</p>', '</h1>', '</h2>', '</h3>', '</h4>'), '', $plaintext); 
      $plaintext = html_entity_decode(stripslashes($plaintext)); 

      //Send the message as HTML 
      $mail->MsgHTML(stripslashes($message)); 
      //Set the plain text version just in case 
      $mail->AltBody = $plaintext; 
      $failed_error="email gagal dikirim"; 
      //Display success or error messages 
      if(!$mail->Send()) 
      { 
       return 'Message send failure: ' . $mail->ErrorInfo; 
        return $failed_error; 
      } 

      else 
      { 
       //You'll usually want to just return true, but for the purposes of this 
       //Example I'm returning the message contents 
      // return $message; 
       return print_r($alamatmail); 
      } 
      endforeach; 

} 
+1

Что вы получите, если вы делаете 'var_dump ($ alamatmail);'? –

+0

они возвращают значение массива Array ([0] => Array ([email] => [email protected]) [1] => Array ([email] => [email protected]) [ 2] => Array ([email] => [email protected])) , и результат верный, –

+0

yup, я пытаюсь это сделать. –

ответ

0

Поскольку вы отправляете же почта для всех получателям нет необходимости перебирать сообщение снова и снова. Все, что вам нужно сделать, это установить отправителя, а затем добавить всех получателей в массив addAddress, а затем закончить цикл.

После этого вы просто создаете свой почтовый ящик и выполняете функцию отправки.

Вы можете использовать это:

<? 
function send_message($from, $to, $subject, $message_content) 
{ 
    require_once "function.php"; 
    require_once('phpmailer/PHPMailerAutoload.php'); 

    //Initiate the mailer class 
    $mail = new PHPMailer(); 

    //Check to see if SMTP creds have been defined 
    if(defined('SMTP_USER') && defined('SMTP_PASS') && defined('SMTP_LOCATION') && defined('SMTP_PORT')) 
    { 
     $mail->IsSMTP(); 
     $mail->Host = SMTP_LOCATION; 
     $mail->SMTPAuth = true; 
     $mail->Port = SMTP_PORT; 
     $mail->Username = SMTP_USER; 
     $mail->Password = SMTP_PASS; 

     if(defined('DEBUG') && DEBUG) 
     { 
      $mail->SMTPDebug = 1; 
     } 
    } 

    $mail->SetFrom('[email protected]', ""); 


    //Set the sender and receiver email addresses 
    $alamatmail = get_mail(); 

    foreach ($alamatmail as $datamail) { 
     $to = $datamail['email']; 

     //We 'can' send to an array, in which case you'll want to explode at comma or line break 
     if(is_array($to)) { 
      foreach($to as $i) { 
       $mail->AddAddress($i, ""); 
      } 
     } 
     else { 
      $mail->AddAddress($to, ""); 
     } 
    } 

    //Set the message subject 
    $mail->Subject = $subject; 

    //Add the message header 
    $message = file_get_contents('email-templates/email-header.php'); 

    //Add the message body 
    $message .= file_get_contents('email-templates/email-body.php'); 

    //Add the message footer content 
    $message .= file_get_contents('email-templates/email-footer.php'); 

    //Replace the codetags with the message contents 
    $replacements = array(
     '({message_subject})' => $subject, 
     '({message_body})' => nl2br(stripslashes($message_content)), 
    ); 
    $message = preg_replace(array_keys($replacements), array_values($replacements), $message); 

    //Make the generic plaintext separately due to lots of css and tables 
    $plaintext = $message_content; 
    $plaintext = strip_tags(stripslashes($plaintext), '<p><br><h2><h3><h1><h4>'); 
    $plaintext = str_replace(array('<p>', '<br />', '<br>', '<h1>', '<h2>', '<h3>', '<h4>'), PHP_EOL, $plaintext); 
    $plaintext = str_replace(array('</p>', '</h1>', '</h2>', '</h3>', '</h4>'), '', $plaintext); 
    $plaintext = html_entity_decode(stripslashes($plaintext)); 

    //Send the message as HTML 
    $mail->MsgHTML(stripslashes($message)); 

    //Set the plain text version just in case 
    $mail->AltBody = $plaintext; 
    $failed_error="email gagal dikirim"; 

    //Display success or error messages 
    if(!$mail->Send()) { 
     return 'Message send failure: ' . $mail->ErrorInfo . $failed_error; 
    } else { 
     //You'll usually want to just return true, but for the purposes of this 
     //Example I'm returning the message contents 
    // return $message; 
     return print_r($alamatmail); 
    } 
} 

Поскольку первый из них включает всех получателей в поле в каждой электронной почте вы можете использовать это (я игнорировал раздел ошибок, так что вы можете добавить его вручную):

<? 
 
function send_message($from, $to, $subject, $message_content) 
 
{ 
 
    require_once "function.php"; 
 
    require_once('phpmailer/PHPMailerAutoload.php'); 
 

 
    //Initiate the mailer class 
 
    $mail = new PHPMailer(); 
 

 
    //Check to see if SMTP creds have been defined 
 
    if(defined('SMTP_USER') && defined('SMTP_PASS') && defined('SMTP_LOCATION') && defined('SMTP_PORT')) 
 
    { 
 
     $mail->IsSMTP(); 
 
     $mail->Host = SMTP_LOCATION; 
 
     $mail->SMTPAuth = true; 
 
     $mail->Port = SMTP_PORT; 
 
     $mail->Username = SMTP_USER; 
 
     $mail->Password = SMTP_PASS; 
 

 
     if(defined('DEBUG') && DEBUG) 
 
     { 
 
      $mail->SMTPDebug = 1; 
 
     } 
 
    } 
 

 
    $mail->SetFrom('[email protected]', ""); 
 

 

 
    //Set the sender and receiver email addresses 
 
    $alamatmail = get_mail(); 
 

 
    //Set the message subject 
 
    $mail->Subject = $subject; 
 

 
    //Add the message header 
 
    $message = file_get_contents('email-templates/email-header.php'); 
 

 
    //Add the message body 
 
    $message .= file_get_contents('email-templates/email-body.php'); 
 

 
    //Add the message footer content 
 
    $message .= file_get_contents('email-templates/email-footer.php'); 
 

 
    //Replace the codetags with the message contents 
 
    $replacements = array(
 
     '({message_subject})' => $subject, 
 
     '({message_body})' => nl2br(stripslashes($message_content)), 
 
    ); 
 
    $message = preg_replace(array_keys($replacements), array_values($replacements), $message); 
 

 
    //Make the generic plaintext separately due to lots of css and tables 
 
    $plaintext = $message_content; 
 
    $plaintext = strip_tags(stripslashes($plaintext), '<p><br><h2><h3><h1><h4>'); 
 
    $plaintext = str_replace(array('<p>', '<br />', '<br>', '<h1>', '<h2>', '<h3>', '<h4>'), PHP_EOL, $plaintext); 
 
    $plaintext = str_replace(array('</p>', '</h1>', '</h2>', '</h3>', '</h4>'), '', $plaintext); 
 
    $plaintext = html_entity_decode(stripslashes($plaintext)); 
 

 
    //Send the message as HTML 
 
    $mail->MsgHTML(stripslashes($message)); 
 

 
    //Set the plain text version just in case 
 
    $mail->AltBody = $plaintext; 
 
    $failed_error="email gagal dikirim"; 
 

 
    foreach ($alamatmail as $datamail) { 
 
     $to = $datamail['email']; 
 

 
     //We 'can' send to an array, in which case you'll want to explode at comma or line break 
 
     if(is_array($to)) { 
 
      foreach($to as $i) { 
 
       $mail2 = clone $mail; 
 
       $mail2->AddAddress($i, ""); 
 
       $mail2->send(); 
 
      } 
 
     } 
 
     else { 
 
      $mail2 = clone $mail; 
 
      $mail2->AddAddress($to, ""); 
 
      $mail2->send(); 
 
     } 
 
    } 
 
}

+2

Хотя это должно сработать, подсказка, почему он работает (а оригинал не подходит), будет хорошей идеей, не так ли? – Burki

+0

Okay Burki Я добавлю его –

+2

На самом деле, вы все равно должны отправлять свое электронное письмо каждому получателю отдельно. – markus

3

в случае успеха, ваша функция закончилась после первой итерации

return print_r($alamatmail); 

Эта линия выходит из функции. Следующая итерация не будет вызываться.

Переместить эту линию после того, как

endforeach; 

и код должен работать (только он не будет печатать целые письма. Вы должны обращаться с этим отдельно)

+0

Я просто использую попытку, используя ваше решение, бурки. Но я все равно получаю тот же результат. Электронная почта отправляет только 1 получателю. –

+0

@yosafatwahyusetyawan вы переместили инструкцию 'return' за пределы вашей строки' foreach'? – Burki

+0

return - это «возврат» результата функции, поэтому выполнение функции заканчивается всякий раз, когда она достигнута. Ваша строка 'return print_r ($ alamatmail);' не имеет ничего общего с тем, что print_r выводит на экран правдиво, так что вы эффективно говорите «возврат вывода на экран», который не будет работать.потерять возврат и просто использовать print_r ($ alamatmail); – Horaland

Смежные вопросы