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


two foreach loops combined for email sending

我正在尝试使用两个文本区域来处理多封电子邮件,一个区域用于"发件人"电子邮件,另一个区域则用于"收件人"电子邮件。逐行合并电子邮件,并相应地发送电子邮件。

例如:

"收件人"列表:

        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>

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

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

在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";
            ...
}

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

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