Morgan Green Morgan Green - 5 months ago 14
PHP Question

Trying to create an array with commas and semicolans

I want to create a loop for my mail system that uses the format

stan.smith@americandadcia.fx, Stan Smith


So that I can pass it through my function

function SendEmail($to,$fromName, $subject, $message)
{
date_default_timezone_set('Etc/UTC');

$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->Debugoutput = 'html';
$mail->Host = smtp_host;
$mail->Port = smtp_port;
$mail->SMTPSecure = smtp_protocol;
$mail->SMTPAuth = true;
$mail->Username = smtp_user;
$mail->Password = smtp_pass;
$mail->setFrom(smtp_user, $fromName);
$mail->addReplyTo(smtp_user, $fromName);
$mail->addAddress($to);
$mail->Subject = $subject;
$mail->msgHTML($message);
$mail->send();
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
}


}


This code is to go through a loop, so say you have
Stan Smith, Roger Smith and Francine Smith the form input would have

stan.smith@americandad.fx, Stan Smith; roger.smith@amongyou.ufo, Roger Smith; francine.smith@desperatehousewives.fox, Francine Smith


The addresses would then be passed into my functions file and ran through the function to send the email

$mail = new MailSystem();
$emails=$_POST['emailTo'];
$email=explode(";",$emails);
foreach($email as $address) {
echo $mail->SendEmail($address, SITE_NAME." Newsletter", $_POST['emailSubject'], $_POST['emailBody']);
}


My Problem is that when the email attempts to send it's going to try to run
$mail->addAddress($address)
and I get the response that it's an invalid address. I can go in and manually set the addAddress with
my email", "My name"
but when it goes through this way it resolves to invalid address.

Answer

On the addAddress() you have to split the receiver name and address. Your function should look like the following:

function SendEmail($to,$fromName, $subject, $message)
{
    date_default_timezone_set('Etc/UTC');

    $mail = new PHPMailer;
    $mail->isSMTP();
    $mail->SMTPDebug = 2;
    $mail->Debugoutput = 'html';
    $mail->Host = smtp_host;
    $mail->Port = smtp_port;
    $mail->SMTPSecure = smtp_protocol;
    $mail->SMTPAuth = true;
    $mail->Username = smtp_user;
    $mail->Password = smtp_pass;
    $mail->setFrom(smtp_user, $fromName);
    $mail->addReplyTo(smtp_user, $fromName);

    //split the to on , to get mail address and receiver name.
    $address = explode(',', $to);

    //check if the name is available.
    if (!isset($address[1])) {
        $mail->addAddress($address[0]);
    } else {
        $mail->addAddress($address[0], $address[1]);
    }

    $mail->Subject = $subject;
    $mail->msgHTML($message);

    //remove the following line because duplicate sending!!!
    //$mail->send();

    if (!$mail->send()) {
        echo "Mailer Error: " . $mail->ErrorInfo;
    } 
}
Comments