SQL查询组特定的列值以为每个用户发送一封电子邮件

时间:2018-11-15 16:03:39

标签: php sql sql-server

我确实需要帮助,我正在花几个小时使我的代码正常工作,但我不能。

我将放置一些代码和输出以轻松了解我的需求和得到的东西。

正如您在输出中看到的,有些用户拥有一张以上的卡,而我需要的是,为每个用户及其卡发送一封电子邮件,例如:

Email #1
To: test1@gmail.com
Text: 
Card 1

Email #2
To: test2@gmail.com
Text: 
Card 2
Card 3

Email #3
To: test3@gmail.com
Text: 
Card 1
Card 2
Card 4

我应该像上面那样发送电子邮件,但是我要在下面发布的代码却没有执行,它发送了电子邮件,但是发送的第一封电子邮件发到了test1@gmail.com和{{ 1}},第二封电子邮件转到test2@gmail.com,它将为每张卡发送一封电子邮件,而不是一封包含所有客户卡的电子邮件

test3@gmai.com

1 个答案:

答案 0 :(得分:0)

<?php

function sendCards( $cards, $email ) {
            if( empty( $cards ) || ! $email ) return;
            $message = '<html><body>';
            $message .= implode('', $cards);
            $message .= '</body></html>';

            $mail->IsSMTP();
            $mail->SMTPDebug = 0;
            $mail->Host = "test-localhost";
            $mail->SMTPAuth = true;
            $mail->SMTPSecure = 'ssl'; 
            $mail->Port = "465";
            $mail->Username = "admin@gmail.com";
            $mail->Password = "passxxxxx";
            $mail->SetFrom('admin@gmail.com', 'admin');
            $mail->addReplyTo("admin@gmail.com");
            $mail->Subject    = "Subject";
            $mail->AltBody    = "Alt";
            $mail->MsgHTML($message);
            $mail->addAddress($email);
            if(!$mail->send()) {
              echo "Mailer Error: " . $mail->ErrorInfo;
            } else {
              echo "Message sent!";
            }
            echo $last_email."</br>";
}

if (!$stm) {
    echo ""; 
} else {
    $last_email = null; 
    $cards = [];
    while ($rows = $stm->fetch())
    {
        $CLTPEmail = isset($rows['Email']) ? $rows['Email'] : NULL;
        if( ! $CLTPEmail ) continue;
        if( $last_email !== $CLTPEmail ) {
            sendCards( $cards, $last_email );
            $cards = [];
            $last_email = $CLTPEmail;
        }

        $CPersonUId = isset($rows['PersonUId']) ? $rows['PersonUId'] : NULL;
        $CType = isset($rows['CardType']) ? $rows['CardType'] : NULL;
        $CNr = isset($rows['CardNr']) ? $rows['CardNr'] : NULL;
        $CValFrom = isset($rows['ValidFrom']) ? $rows['ValidFrom'] : NULL;
        $CValUntil = isset($rows['ValidUntil']) ? $rows['ValidUntil'] : NULL;
        $CLTCCTime = isset($rows['LastTccTime']) ? $rows['LastTccTime'] : NULL;

        if ($CValUntil != NULL)
        {
            $time1 = strtotime($CValUntil);
            $mytime1 = date("d/m/Y", $time1);
            $CValUntil = $mytime1;
        }else{
            $mytime1 = $CValUntil;
        }

        if($CType == 6){
            $CType = 'Type 1';
        }elseif($CType == 5){
            $CType = 'Type 2';
        }elseif($CType == 1){
            $CType = 'Type 3';
        }
        $cards [] = "<p>Cartão nº<b>".$CNr."</b> válido até <b>".$mytime1." Tipo: ".$CType."</b></p>";
    }

    if( ! empty( $cards )) {
        sendCards( $cards, $last_email )
    }
}