Lieutenant Dan
Lieutenant Dan

Reputation: 8284

php mailer add confirmation email to inputted address and form submit

I'm really trying to keep both functionality -- form fields filled out > form submit > goes to web masters email address with the information.

I'm failing to add a second functionality; I would like the user to be sent a custom confirmation message after form submit (all users get same default message) -- this message is emailed to the address inserted by user in 'email' field. I've gotten this; but by doing so, I killed my original functionality; I would like to maintain both; thus far I can get one to work, but then the other functionality dies -- currently it just sends confirmation to both emails below.

<?php

/* config start [email protected]*/

$emailAddress = '[email protected]'; // form goes here
$to      = $_POST['email']; // user gets confirmation
$message = 'Thank you for submitting the form on our website.!';

/* config end */


require "phpmailer/class.phpmailer.php";

session_name("fancyform");
session_start();    


foreach($_POST as $k=>$v)
{
    if(ini_get('magic_quotes_gpc'))
    $_POST[$k]=stripslashes($_POST[$k]);

    $_POST[$k]=htmlspecialchars(strip_tags($_POST[$k]));
}


$err = array();

if(!checkLen('name'))
    $err[]='The name field is too short or empty!';

if(!checkLen('email'))
    $err[]='The email field is too short or empty!';
else if(!checkEmail($_POST['email']))
    $err[]='Your email is not valid!';

/* if(!checkLen('phone'))
    $err[]='The phone field is too short or empty!'; */

/*if(!checkLen('subject'))
    $err[]='You have not selected a subject!';*/

/* if(!checkLen('message'))
    $err[]='The message field is too short or empty!';*/

if((int)$_POST['captcha'] != $_SESSION['expect'])
    $err[]='The captcha code is wrong!';


if(count($err))
{
    if($_POST['ajax'])
    {
        echo '-1';
    }

    else if($_SERVER['HTTP_REFERER'])
    {
        $_SESSION['errStr'] = implode('<br />',$err);
        $_SESSION['post']=$_POST;

        header('Location: '.$_SERVER['HTTP_REFERER']);
    }

    exit;
}


$msg=
'Name:  '.$_POST['name'].'<br />
Phone:  '.$_POST['phone'].'<br />
Email:  '.$_POST['email'].'<br />
IP: '.$_SERVER['REMOTE_ADDR'].'<br /><br />
Referred By:    '.$_POST['referer'].'<br /><br />
Message:<br /><br />

'.nl2br($_POST['message']).'

';


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

$mail->AddReplyTo($_POST['email'], $_POST['name']);
$mail->AddAddress($emailAddress);
$mail->addAddress($to);  // why can't both coexist?
$mail->SetFrom($_POST['email'], $_POST['name']);
$mail->Subject = "A new Bridgetower.com Lead".mb_strtolower($_POST['subject'])." from ".$_POST['name']." | Via your contact form feedback";

$mail->MsgHTML($msg);
$mail->msgHtml($message); // why can't both coexist?

$mail->Send();

// $to      = $_POST['email'];
// $message = 'Thank you for submitting the form on our website.!';


unset($_SESSION['post']);

if($_POST['ajax'])
{
    echo '1';
}
else
{
    $_SESSION['sent']=1;

    if($_SERVER['HTTP_REFERER'])
        header('Location: '.$_SERVER['HTTP_REFERER']);

    exit;
}

function checkLen($str,$len=2)
{
    return isset($_POST[$str]) && mb_strlen(strip_tags($_POST[$str]),"utf-8") > $len;
}

function checkEmail($str)
{
    return preg_match("/^[\.A-z0-9_\-\+]+[@][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z]{1,4}$/", $str);
}

?>

Code I added (which works, but overrides base form submit)

Grab email inputted in email field within online form > send confirmation there after submit.

If I take the below lines out; my form works normally; user fills out form, sends to specified default email address - I just want to add in the confirmation message, and maintain the form working properly as well.


$to      = $_POST['email']; // user gets confirmation
$message = 'Thank you for submitting the form on our website.!';


$mail->addAddress($to);  // why can't both coexist?

$mail->msgHtml($message); // why can't both coexist?

Maybe the question is how to allow multiple $mail->MsgHTML to send?

Original code; I'm trying to add second functionality on to:

<?php

/* config start [email protected]*/

$emailAddress = '[email protected]';

/* config end */


require "phpmailer/class.phpmailer.php";

session_name("fancyform");
session_start();    


foreach($_POST as $k=>$v)
{
    if(ini_get('magic_quotes_gpc'))
    $_POST[$k]=stripslashes($_POST[$k]);

    $_POST[$k]=htmlspecialchars(strip_tags($_POST[$k]));
}


$err = array();

if(!checkLen('name'))
    $err[]='The name field is too short or empty!';

if(!checkLen('email'))
    $err[]='The email field is too short or empty!';
else if(!checkEmail($_POST['email']))
    $err[]='Your email is not valid!';

/* if(!checkLen('phone'))
    $err[]='The phone field is too short or empty!'; */

/*if(!checkLen('subject'))
    $err[]='You have not selected a subject!';*/

/* if(!checkLen('message'))
    $err[]='The message field is too short or empty!';*/

if((int)$_POST['captcha'] != $_SESSION['expect'])
    $err[]='The captcha code is wrong!';


if(count($err))
{
    if($_POST['ajax'])
    {
        echo '-1';
    }

    else if($_SERVER['HTTP_REFERER'])
    {
        $_SESSION['errStr'] = implode('<br />',$err);
        $_SESSION['post']=$_POST;

        header('Location: '.$_SERVER['HTTP_REFERER']);
    }

    exit;
}


$msg=
'Name:  '.$_POST['name'].'<br />
Phone:  '.$_POST['phone'].'<br />
Email:  '.$_POST['email'].'<br />
IP: '.$_SERVER['REMOTE_ADDR'].'<br /><br />
Referred By:    '.$_POST['referer'].'<br /><br />
Message:<br /><br />

'.nl2br($_POST['message']).'

';


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

$mail->AddReplyTo($_POST['email'], $_POST['name']);
$mail->AddAddress($emailAddress);
$mail->SetFrom($_POST['email'], $_POST['name']);
$mail->Subject = "A new Bridgetower.com Lead".mb_strtolower($_POST['subject'])." from ".$_POST['name']." | Via your contact form feedback";

$mail->MsgHTML($msg);

$mail->Send();


unset($_SESSION['post']);

if($_POST['ajax'])
{
    echo '1';
}
else
{
    $_SESSION['sent']=1;

    if($_SERVER['HTTP_REFERER'])
        header('Location: '.$_SERVER['HTTP_REFERER']);

    exit;
}

function checkLen($str,$len=2)
{
    return isset($_POST[$str]) && mb_strlen(strip_tags($_POST[$str]),"utf-8") > $len;
}

function checkEmail($str)
{
    return preg_match("/^[\.A-z0-9_\-\+]+[@][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z]{1,4}$/", $str);
}

?>

Upvotes: 0

Views: 3495

Answers (2)

Stephen
Stephen

Reputation: 89

You can send multiple emails with the same instance with this code. (Modified code from Amazon SES.)

$mail = new PHPMailer(true);

try {
    // Specify the SMTP settings.
    $mail->isSMTP();
    $mail->setFrom($sender, $senderName);
    $mail->Username   = $usernameSmtp;
    $mail->Password   = $passwordSmtp;
    $mail->Host       = $host;
    $mail->Port       = $port;
    $mail->SMTPAuth   = true;
    $mail->SMTPSecure = 'tls';
    $mail->addAddress($recipient); // Original content added here
    $mail->isHTML(true);
    $mail->Subject    = $subject;
    $mail->Body       = $bodyHtml;
    $mail->AltBody    = $bodyText;
    $mail->Send(); // The content of the form sent here
    echo "Order Submitted: ";
    $mail->ClearAddresses(); // Clear addresses
    $mail->addAddress($customerEmail); // Email address entered on form
    $mail->isHTML(true);
    $mail->Subject    = $confirmationSubject; // Custom subject
    $mail->Body       = $confirmationBodyHtml; // Custom reply
    $mail->AltBody    = $confirmationBodyText; // Text only custom reply
    $mail->Send(); // Send confirmation email
    echo "Confirmation Sent";
    //echo "Email sent!" , PHP_EOL;
} catch (phpmailerException $e) {
    echo "An error occurred. {$e->errorMessage()}", PHP_EOL; //Catch errors from PHPMailer.
} catch (Exception $e) {
    echo "Email not sent. {$mail->ErrorInfo}", PHP_EOL; //Catch errors from Amazon SES.
}

Upvotes: 0

Jordan
Jordan

Reputation: 5445

You can't send two mails with the same instance - you need to reassign $mail to a new instance of the PHPMailer class:

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

$mail->AddReplyTo($_POST['email'], $_POST['name']);
$mail->AddAddress($emailAddress);

$mail->SetFrom($_POST['email'], $_POST['name']);
$mail->Subject = "A new Bridgetower.com Lead".mb_strtolower($_POST['subject'])." from ".$_POST['name']." | Via your contact form feedback";

$mail->MsgHtml($message);

$mail->Send();

///////////////////////////////////////////////////////////////
// then create new instance.. 
///////////////////////////////////////////////////////////////

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

$mail->AddReplyTo($_POST['email'], $_POST['name']);
$mail->AddAddress($to);
$mail->SetFrom($_POST['email'], $_POST['name']);
$mail->Subject = "A new Bridgetower.com Lead".mb_strtolower($_POST['subject'])." from ".$_POST['name']." | Via your contact form feedback";

$mail->MsgHtml($message); // why can't both coexist?

$mail->Send();

Upvotes: 1

Related Questions