2012-03-12 83 views
1

我试图将两个文本区域与多个电子邮件,一个与“从”电子邮件,一个与“到”电子邮件。逐行组合电子邮件并相应地发送电子邮件。两个foreach循环合并发送电子邮件

例:

“要” 的文章:

 [email protected] 

     [email protected] 

     [email protected] 

“从” 列表:

 [email protected] 

     [email protected] 

     [email protected] 

我希望有一个电子邮件发送到:

[email protected] from [email protected] 

    [email protected] from [email protected] 

    [email protected] from [email protected] 

任何帮助将不胜感激。先谢谢了。

以下是我到目前为止的脚本,它通过一封电子邮件发送给多个电子邮件。

<?php 
if (isset($_POST['submit'])) 
{ 

    // Execute this code if the submit button is pressed. 
    $raw_email_account = $_POST['email_from']; 
    $email = $_POST['email_to']; 
    $sent = ""; 
    $invalid = ""; 

    //Separating each line to be read by foreach 
    $list = explode("\n",$email); 

    //Rendering the separeted data from each line 
    foreach($list AS $data) { 
       //Separating each line to be read by foreach 
      $item = explode(":",$data); 
      $mail_body = '<html><body>email here</body></html>'; 
       $subject = "subject here"; 
       $headers = "From:".$raw_email_account."\r\n"; 
       $headers .= "Content-type: text/html\r\n"; 
       $to = $item[0]; 

       $mail_result = mail($to, $subject, $mail_body, $headers); 

      if ($mail_result) { 
       $valid++; 
      } else { 
        // write into an error log if the mail function fails 
        $invalid++; 
      } 
    } 

} 
?> 
<html> 
<head> 
</head> 
<body> 
<form action="email_sender.php" method="POST"> 
<div align="center">From Email Accounts: <textarea name="email_from" cols="100" rows="60"></textarea></div><br /> 
<div align="center">To Email Accounts: <textarea name="email_to" cols="100" rows="60">  </textarea></div><br /> 
<div align="center"><input type="submit" name="submit"></div> 
<br> 
Valids: <?php echo $valid;?> 
<br> 
Invalids: <?php echo $invalid;?> 
</body> 
</html> 

回答

1

在foreach循环之前添加提供相同计数$email$raw_email_account arrays的逻辑。

$list = explode("\n",$email); 
$list2 = explode("\n", $raw_email_account); 

foreach($list AS $key=>$data) { 
      ... 
      $headers = "From:".$list2[$key]."\r\n"; 
      ... 
} 
+0

这工作就像一个魅力,谢谢你先生:) – 2012-03-13 02:24:59

+0

不客气! – Pave 2012-03-13 11:40:01

0

您可以使用array_combine()轻松解决该问题。

在这种情况下,您首先组合这两个数组,然后遍历生成的数组以执行发送电子邮件操作。

+1

你真的不需要'array_combine'。这绝对是一种额外的操作。只需匹配两个数组的密钥就足够了。 – netcoder 2012-03-12 18:41:16

+0

同意。刚才说了一下我现在想到的。但是,如果两个数组使用简单的数字键格式,则这是可能的。 – 2012-03-12 18:43:18

2

如果数组默认情况下,索引将重合。所以你可以做这样的事情。

$toList = array(..); 
$fromList = array(...); 

foreach($toList as $key => $value) { 
    $toAddress = $value; 
    $fromAddress = $fromList[$key]; 
    //.. 
    //.. Go on with you mail function 
}