两个foreach循环组合用于电子邮件发送

时间:2012-03-12 18:35:28

标签: php email loops foreach

我正在尝试使用多个电子邮件进行两个文本区域,一个带有“发件人”电子邮件,另一个带有“收件人”电子邮件。逐行合并电子邮件并相应地发送电子邮件。

例如:

“要”列出:

        mike@gmail.com

        nick@hotmail.com

        adam@yahoo.com

“来自”列表:

        ashley@gmail.com

        brittney@yahoo.com

        racheal@hotmail.com

我想发送电子邮件至:

   mike@gmail.com from ashley@gmail.com

   nick@hotmail.com from brittney@yahoo.com

   adam@yahoo.com from racheal@hotmail.com

非常感谢任何帮助。谢谢你提前。

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

 <?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>

3 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分: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";
            ...
}

答案 2 :(得分:0)

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

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