dongyu1918 2018-04-03 23:15
浏览 91

PHPmailer动态数据到多个邮件?

I am coding on a system where the admin should be able to click a button and send a mail to all users. When i click the a href and redirect with type = 2 it sends the mail to all accounts but the content which is supposed to be dynamic just returns the email of the last user in the array.

<?php
include "core/init.php"; 
error_reporting(E_ALL);

date_default_timezone_set('Etc/UTC');
require 'phpmailer/PHPMailerAutoload.php'; 

$mail = new PHPMailer; 
$mail->isSMTP(); 

$mail->SMTPDebug    = 0; 
$mail->Debugoutput  = 'html'; 
$mail->Host         = 'smtprotocl'; 
$mail->Port         = 587; 
$mail->SMTPSecure   = 'tls'; 
$mail->SMTPAuth     = true; 
$mail->Username     = "mymail@mail.dk"; 
$mail->Password     = "password";
$mail->CharSet      = 'UTF-8';

$mail->setFrom('mymail@mail.dk', 'nameofmailholder'); 

if ($_GET["type"]) {
     if ($_GET["type"] == 2){

        $confirmede = 0;
        $getVendorc = $db->prepare("SELECT * FROM db"); 
        $getVendorc->execute();
        $vresultc = $getVendorc->get_result();
        $getVendorc->store_result();

        while ($rowing = $vresultc->fetch_assoc()) {

            $removeSpace = explode(" ",     decrypt($rowing["email"]));
            $Uemail      = implode("+", $removeSpace);

            $mail->addReplyTo($Uemail); 
            $mail->addAddress($Uemail);

        }

        $mail->isHTML(true);  

        $mail->Subject = 'welcome';


        $mail->Body    = '<a href="website?id='. encrypt($Uemail) .'" target="_blank"><button >Bekræft email</button></a>';

    } else {
        urlLocation("index");
    }
}

$mail->AltBody = 'aa';

if($mail->send()) {
    urlLocation("../../index");
}?>
  • 写回答

1条回答 默认 最新

  • douhong1703 2018-04-03 23:42
    关注

    Either create the email (using PHPMailer functions) and send it INSIDE the loop (which is what you should do), or do the following if you want to send one email to all recipients at once (without revealing emails to anyone, because it's BCC). I don't recommend this, but I suppose it could work.

    $mail->addAddress("fake@address.com");
    $mail->addBCC($email1, $email2, $email3, $email4);
    

    That should work for sending the same email to multiple recipients, in one email without revealing all of the emails to everyone.

    Personally, I use wuMail... It makes using PHPMailer a lot easier, especially with SMTP. Here's my setup, with login details changed obviously... I'll explain how it works below, but you would need to download wuMail (link at bottom) so that the files (for PHPMailer) are referenced correctly by config.php & wuMail.php... The code blocks below are references, but can't be used standalone without the rest of the wuMail download.

    The first thing that happens is that we set the system defaults... These are used in case certain email parameters are not supplied to wuMail(). This is a fail safe, in case you want a default to address in case part of the system attempts to use wuMail() without supplying to address.. This would let you discover those types of bugs quickly.

    The following is the code in config.php... You require config.php in any file that you want to use wuMail() function in (to send mail). Config will set the settings in advance & then bring in the wuMail.php file itself. So don't include the wuMail.php file, just config.php!

    <?php
    /*
    NOTE: These settings have been prepared by
    WUBUR.COM / WUBUR LLC / BILLY LOWERY / WILL PASSMORE
    */
    
    # DO NOT REMOVE:
    $wuMail_Config = new stdClass();
    
    //SENDER CONFIG SETTINGS - YOU CAN CHANGE THESE:
    // ----> Note: This current configuration has a form sending to the same address each time
    // ----> This could obviously be adapted to allow for emails being sent elsewhere
    $wuMail_Config->SiteName = 'Wubur.com';
    
    //SERVER CONFIG SETTINGS - YOU CAN CHANGE THESE:
    $wuMail_Config->isSMTP = true;                                   // Set mailer to use SMTP (TRUE / FALSE)
    $wuMail_Config->Host = 'smtp.gmail.com';                                            // Specify main and backup SMTP servers
    $wuMail_Config->SMTPAuth = true;                                // Enable SMTP authentication (TRUE / FALSE)
    $wuMail_Config->AuthType = 'LOGIN';                                                         // Authentification type... ex: PLAIN, LOGIN
    $wuMail_Config->Username = 'USERNAME@gmail.com';                    // Only blank for GoDaddy's servers
    $wuMail_Config->Password = 'PASSWORD';                          // Only blank for GoDaddy's servers
    $wuMail_Config->SMTPSecure = 'ssl';                            // ('tls', 'ssl' or false)
    $wuMail_Config->Port = 465;                                    // TCP port to connect to
    $wuMail_Config->Exceptions = true;                                                      // true/false, if Exceptions enabled
    $wuMail_Config->SMTPDebug = 0;                                 // Enable verbose debug output ~~ must be 0 in production environment
    
    //MESSAGE CONFIG SETTINGS - YOU CAN CHANGE THESE:
    $wuMail_Config->DefaultToAddress = 'to@email.com';
    $wuMail_Config->DefaultToName = 'To Name';
    $wuMail_Config->DefaultCC = false; // no default CC
    $wuMail_Config->DefaultBCC = false;  // no default BCC
    $wuMail_Config->DefaultFromAddress = 'from@email.com';
    $wuMail_Config->DefaultFromName = 'From Name';
    $wuMail_Config->DefaultReplyAddress = 'replyaddress@email.com';
    $wuMail_Config->DefaultReplyName = 'Reply Name';
    $wuMail_Config->DefaultSubject = 'Default Subject';
    
    # MESSAGE / HTML VERSION CONFIG SETTINGS - YOU CAN CHANGE THESE. BE CAREFUL:
    $wuMail_Config->DefaultMessage = 'Default Message (Message Not Supplied)';
    $wuMail_Config->ForceHTML = true; // (recommended: true)
    // If set to TRUE, and no HTML version of message is supplied to wuMail function, use the HTML template below...Otherwise use HTML supplied to wuMail function if it is supplied.
    // If set to FALSE, and no HTML version of message is supplied to wuMail function, simply display a non-HTML message to recipient. If HTML version is supplied, HTML version will be used instead of template
    # DefaultHTML: Simply use {!messageInsert!} to insert the regular non-HTML message into the template. {!siteNameInsert!} will insert the config site name.
    $wuMail_Config->DefaultHTML = '
    <div>
        <center><a href="site.com"><img style="width:350px; height:auto; margin-bottom:25px;" src="site.com/logo.png" alt="Site Name" /></a></center>
        <div style="width:100%; color:white; background-color:#c02026; font-weight:500; padding:10px;">Important Information</div>
        <div style="width:100%; padding:25px; color:black; background-color:#f2f2f2;">
            {!messageInsert!}
        </div>
    </div>
    ';
    # NOTE: The 'HTML' key in the options data array for wuMail can be a template with {!messageInsert!} or {!siteNameInsert!} as variables!
    
    // PHPMailer Path Settings:
    $wuMail_Path = ""; // path from root dir for site access
    
    // DO NOT REMOVE:
    require $wuMail_Path . "wuMail.php";
    ?>
    

    The URL & logo image in the template should obviously be updated... This is the default template if someone supplies an email message without the HTML version. This is so every email can use HTML templates when allowed, even if developers don't properly use one in the first place :) System settings for the win!

    Next we have wuMail.php itself...

    <?php
    
    /*
    NOTE: These settings have been prepared by
    WUBUR.COM / WUBUR LLC / BILLY LOWERY / WILL PASSMORE
    */
    
    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\Exception;
    
    require $wuMail_Path . 'src/Exception.php';
    require $wuMail_Path . 'src/PHPMailer.php';
    require $wuMail_Path . 'src/SMTP.php';
    
    function wuMail($data, $multi = false){ 
        global $wuMail_Config;
    
        if(!is_array($data)){
            $useDefaults = true;
        } else {
            $useDefaults = false;
        }
    
        $mailSettings = array(
            "TOADDRESS" => $wuMail_Config->DefaultToAddress,
            "TONAME" => $wuMail_Config->DefaultToName,
            "CC" => $wuMail_Config->DefaultCC,
            "BCC" => $wuMail_Config->DefaultBCC,
            "SUBJECT" => $wuMail_Config->DefaultSubject,
            "MESSAGE" => $wuMail_Config->DefaultMessage,
            "HTML" => $wuMail_Config->DefaultHTML,
            "FROMADDRESS" => $wuMail_Config->DefaultFromAddress,
            "FROMNAME" => $wuMail_Config->DefaultFromName,
            "REPLYADDRESS" => $wuMail_Config->DefaultReplyAddress,
            "REPLYNAME" => $wuMail_Config->DefaultReplyName
        );
            # NOTES: THE FOLLOWING CAN BE ARRAYS: ToAddress, ToName (arr key must match ToAddress arr), CC, BCC
            # IN FUTURE, YOU CAN LINE UP EMAILS TO SEND SEPARATELY BY SIMPLY MAKING MULTIDIMENSIONAL ARRAY OF DATA, AND SETTING PARAM 2 (MULTI) EQUAL TO TRUE IN WUMAIL
    
        if($useDefaults !== true){
            $submittedOpts = array();
            foreach($data as $submittedOption => $submittedValue){
                $submittedOptionUPPER = strtoupper($submittedOption);
                $submittedOpts[] = $submittedOptionUPPER;
                if(isset($mailSettings[$submittedOptionUPPER])){
                    $mailSettings[$submittedOptionUPPER] = $data[$submittedOption];
                } else {
                    echo "ERROR: SUBMITTED MAIL OPTION NOT ACCEPTED";
                }
            }
    
            if(($mailSettings['TOADDRESS'] !== $wuMail_Config->DefaultToAddress) && !in_array('TONAME', $submittedOpts)){ # To address supplied, but no to name supplied
                # do not use a toName...
                $mailSettings['TONAME'] = false;
            }
    
            if(($mailSettings['FROMADDRESS'] !== $wuMail_Config->DefaultFromAddress) && !in_array('FROMNAME', $submittedOpts)){ # From address supplied, but no fromname supplied
                $mailSettings['FROMNAME'] = false;
                # do not use fromname below, because the supplied from address differs from the default in settings
            }
    
            if(($mailSettings['REPLYADDRESS'] !== $wuMail_Config->DefaultFromAddress) && !in_array('REPLYNAME', $submittedOpts)){ # Reply address supplied, but no replyname supplied
                $mailSettings['REPLYNAME'] = false;
                # do not use replyname below, because the supplied reply address differs from the default in settings
            }
        } # useDefaults !== true
    
        $mail = new PHPMailer($wuMail_Config->Exceptions);
        try {
            //Server Settings (from PHPMailer/config.php) - Change in config.php file, not here!
            $mail->SMTPDebug = $wuMail_Config->SMTPDebug;
            if($wuMail_Config->isSMTP === true){ $mail->isSMTP(); }
            $mail->Host = $wuMail_Config->Host;
            $mail->SMTPAuth = $wuMail_Config->SMTPAuth;
            $mail->AuthType = $wuMail_Config->AuthType;
            $mail->Username = $wuMail_Config->Username;
            $mail->Password = $wuMail_Config->Password;
            $mail->SMTPSecure = $wuMail_Config->SMTPSecure;
            $mail->Port = $wuMail_Config->Port;
    
        //Recipients
            if($mailSettings['FROMNAME'] !== false){
                $mail->setFrom($mailSettings['FROMADDRESS'], $mailSettings['FROMNAME']);
            } else {
                $mail->setFrom($mailSettings['FROMADDRESS']);
            }
    
            if($mailSettings['TONAME'] !== false){
                $mail->addAddress($mailSettings['TOADDRESS'], $mailSettings['TONAME']);
            } else {
                $mail->addAddress($mailSettings['TOADDRESS']);
            }
    
            if($mailSettings['REPLYNAME'] !== false){
                $mail->addReplyTo($mailSettings['REPLYADDRESS'], $mailSettings['REPLYNAME']);
            } else {
                $mail->addReplyTo($mailSettings['REPLYADDRESS']);
            }
    
            if($mailSettings['REPLYNAME'] !== false){
                $mail->addReplyTo($mailSettings['REPLYADDRESS'], $mailSettings['REPLYNAME']);
            } else {
                $mail->addReplyTo($mailSettings['REPLYADDRESS']);
            }
    
            if($mailSettings['CC'] !== false){
                $mail->addCC($mailSettings['CC']);
            }
    
            if($mailSettings['BCC'] !== false){
                $mail->addCC($mailSettings['BCC']);
            }
    
            //Attachments
            #$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
            #$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
    
            if($wuMail_Config->ForceHTML !== true && !in_array("HTML", $submittedOpts)){ # ForceHTML is not enforced, and HTML not submitted.... Use plain text message:
                $mailSettings['HTML'] = $mailSettings['MESSAGE'];
                $mail->isHTML(false);
            } else if($wuMail_Config->ForceHTML === true && !in_array("HTML", $submittedOpts)){ # ForceHTML is true, and wuMail received no HTML template to use: ... use default:
                $templateVarFind = array("{!messageInsert!}", "{!siteNameInsert!}");
                $templateVars = array($mailSettings['MESSAGE'], $wuMail_Config->SiteName);
                $mailSettings['HTML'] = str_replace($templateVarFind, $templateVars, $mailSettings['HTML']); // insert variables into default wuMail HTML template
                $mail->isHTML(true);
            } else {
                $mail->isHTML(true);
            }
    
            $mail->Subject = $mailSettings['SUBJECT'];
    
            if($mailSettings['HTML'] == $mailSettings['MESSAGE']){
                $mail->Body = $mailSettings['MESSAGE'];
            } else {
                $mail->Body = $mailSettings['HTML'];
                $mail->AltBody = $mailSettings['MESSAGE'];
            }
    
            $mail->send();
            return true;
    
        } catch (Exception $e) {
                return 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo;
        }
    } // wuMail end
    ?>
    

    Finally, after all of this is setup in config.php and wuMail.php, we can begin to use the wuMail() function

    require_once "wuMail/config.php"; 
    $mailData = array(
        "TOADDRESS" => "userToSendTo@email.com",
        "TONAME" => "First Name",
        "SUBJECT" => "Registration",
        "MESSAGE" => "Hello this is a message",
        "HTML" => "Hello this is a <strong>message</strong>",
        "FROMADDRESS" => "from@website.com",
        "FROMNAME" => "Admin Mail",
        "REPLYADDRESS" => "donotreply@email.com"
    );
    if(wuMail($mailData) === true){
     // mail sent 
    } else { 
     // mail not successful, change SMTPDebug to = 4 in config.php to bug test
    }
    

    As you can see, not all parameters have to be supplied...In the $mailData array you can supply:

    $mailSettings = array(
            "TOADDRESS" => $wuMail_Config->DefaultToAddress,
            "TONAME" => $wuMail_Config->DefaultToName,
            "CC" => $wuMail_Config->DefaultCC,
            "BCC" => $wuMail_Config->DefaultBCC,
            "SUBJECT" => $wuMail_Config->DefaultSubject,
            "MESSAGE" => $wuMail_Config->DefaultMessage,
            "HTML" => $wuMail_Config->DefaultHTML,
            "FROMADDRESS" => $wuMail_Config->DefaultFromAddress,
            "FROMNAME" => $wuMail_Config->DefaultFromName,
            "REPLYADDRESS" => $wuMail_Config->DefaultReplyAddress,
            "REPLYNAME" => $wuMail_Config->DefaultReplyName
        );
    

    As you can see, there are quite a few custom parameters you can enter into wuMail($data) when you want to send mail. If you leave any out, it defaults to the settings in config.php for that specific setting! The reply address/name & to address/name & from name/address all are dynamic so that if you supply a custom address (but no name), it will not mismatch the custom email with the default name. It will simply send it with that information as blank.

    You can download wuMail if you want it at:

    http://nerdi.org/stackoverflow/wuMail.zip

    wuMail comes with PHPMailer packaged in and is 100% free... obviously :)

    评论

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源