Confirmation code wont copy to phpmailer - php

Ok, my problem is that when i try to make my confirm link with the random code that i already created, it wont pass to the Confirmation mail. However the confirm code, still inserts to the database without problems. This is my code:
function NewUser()
{
$user = $_POST['user'];
$pass = $_POST['pass'];
$confirm = md5(uniqid(rand(), true));
$success = "INSERT INTO members(user,pass,'$confirm')";
$data = mysql_query ($success)or die(mysql_error());
if($data)
{if($data)
{
SendUserConfirmationEmail($confirm);
echo "<div class ='verdanacenter'><img src='img/bienvenido.png' title='Enhorabuena'/><br><br><br><font face ='verdana'>Welcome <b>$name $lname</b> !!!<br>Success.<br><br>Soon u will receive a confirmation msg to <b>$email</b>";
}
else
{
echo "<div class ='verdanacenter'><img src='img/alerta.png' title='Error'/><br><br><br><font face ='verdana'>Fatal Error !!!";
}
}
function SendUserConfirmationEmail($confirmcode)
{
require 'PHPMailerAutoload.php';
$mail = new PHPMailer();
$mail->isSendmail();
$mail->setFrom('info#rene.org', 'Rene');
$mail->addAddress($_POST['email'],$_POST['name']);
$mail->Subject = 'Welcome';
$mail->IsHTML(true);
$confirmcode = $confirm;
$mail->Body = '<p align="left"> Welcome <b>'.$_POST['name'].'</b>,</p><p align="justify">This is ur confirmation code:</p>
<p align="left">CONFIRMAR,</p>
<p align="left">Regards,<br>
Admin.<br>
www.rene.org</p>';
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
}
The thing is that, when i register, i receive the email, but without the random code ($confimcode). It appears: "http://www.rene.org/confirmar.php?code=" instead of "http://www.rene.org/confirmar.php?code=A23B45423545V6764542543" What am i missing guys? PLEASE HELP.

This is called scope.
The function can't see variables from outside of itself. To pass that code to the function you include it in a parameter:
function SendUserConfirmationEmail($confirmcode){
...
when you call the function you pass your variable:
SendUserConfirmationEmail($confirm);
Anywhere inside your function, that value will be available as $confirmcode
Edit: Also just noticed you have a function inside a function. Don't do that, just make them separate.

Related

Form to Email PHP Validation fallback using PHPMailer

i have a basic contact form on a website. i need to send the form results to 2 email addresses... 1) me, & 2) a confirmation to the person who submitted the form. the form results sent to the submitter has a different message in it.
i plan to add jQuery validation & Ajax but first i want to get the PHP to work. so i don't think i need a lot of PHP validation, just a basic - if critical fields are empty, then error message, as a fallback.
i'm using PHPMailer but unfortunately their documentation is sorely lacking for someone of my lack-of-php skills. but after much google'ing, i've been able to piece together something that mostly works. here is my code utilizing a small form (more fields to come later).
this DOES send the form to both email addresses - great!
the part i'm having trouble with is the validation & error/success messages.
if i just use the return $mail->send(); at the end of the function sendemail section, it sends fine. but if i try to submit the form without anything in the fields, nothing happens. so i tried adding this if(!$mail->send()) {...else...} piece i found somewhere, and it also works with valid form info, but not if empty.
so, what should i use instead of this? or would it be something different to the end if/else part?
<?php
if (isset($_POST['submit'])) {
date_default_timezone_set('US/Central');
require 'PHPMailer-5.2.26/PHPMailerAutoload.php';
function sendemail(
$SK_emailTo,
$SK_emailSubject,
$SK_emailBody
) {
$mail = new PHPMailer;
$mail->setFrom('myEmail#gmail.com', 'My Name');
$mail->addReplyTo($_POST['email'], $_POST['name']);
$mail->addAddress($SK_emailTo);
$mail->Subject = $SK_emailSubject;
$mail->Body = $SK_emailBody;
$mail->isHTML(true);
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->Username = 'myEmail#gmail.com';
$mail->Password = 'myPwd';
//return $mail->send(); //this works by itself, without IF/ELSE, but doesn't return error if empty form fields
if(!$mail->send()) {
return 'There is a problem' . $mail->ErrorInfo;
}else{
return 'ok'; // this works but i don't know why
}
} //end function sendemail
// form fields to variables
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
// from function sendmail to ASSIGN VALUES to...
/* $SK_emailTo,
SK_emailSubject,
$SK_emailBody */
if (sendemail(
'myEmail#address.com',
'First email subject',
'Form results to me...
<br><br>'.$message
)) {
sendemail(
$email,
'Second email subject',
'Confirmation email to person who submitted the form...
<br><br>'.$message
);
$msg = 'Email sent!';
} else {
$msg = 'Email failed!' . $mail->ErrorInfo;
}
} //end if submit
?>
as a sidenote, why does the return 'ok'; work? what does the 'ok' part attach to?
thanks!
//////////////////////// EDIT: NEW INFO BUT STILL NOT SOLVED ////////////////////////
based on the suggestions & edits by Mauro below (and in that posts comments), here is where i'm at now...
<?php
if (isset($_POST['submit'])) {
date_default_timezone_set('US/Central');
require 'PHPMailer-5.2.26/PHPMailerAutoload.php';
function sendemail(
$SK_emailTo,
$SK_emailSubject,
$SK_emailBody
) {
$mail = new PHPMailer(true);
$mail->setFrom('myEmail#gmail.com', 'My Name');
$mail->addReplyTo($_POST['email'], $_POST['name']);
$mail->addAddress($SK_emailTo);
$mail->Subject = $SK_emailSubject;
$mail->Body = $SK_emailBody;
$mail->isHTML(true);
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->Username = 'myEmail#gmail.com';
$mail->Password = 'myPwd';
return $mail->send();
} //end function sendemail
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
try {
sendemail(
'myEmail#address.com',
'First email subject',
'Form results to me...
<br><br>'.$message
);
sendemail(
$email,
'Second email subject',
'Confirmation email to person who submitted the form...
<br><br>'.$message
);
echo 'Email sent!';
} //end try
catch (phpmailerException $e) { //catches PHPMailer errors
echo 'There is a problem; the message did NOT send. Please go back and check that you have filled in all the required fields and there are no typos in your email address.';
echo $e->errorMessage();
}
catch (Exception $e) { //catches validation errors
echo 'There is a problem; the message did NOT send. Please either go back and try again or contact us at email#address.com';
echo $e->getMessage();
}
function validateEmpty($string, $name = 'name') {
$string = trim($string);
if ($string == '') {
throw new Exception(sprintf('%s is empty.', $name));
}
}
} //end if submit
?>
STILL...
1) Mauro suggested i log the error message using use error_log(). how do i do that? is that what produces the text file of error messages in the ftp directory?
2) Mauro also suggested using an $error & $success flag. what is that & how do i do it?
3) i want to have the custom error message in the above catch if the "name" &/or "email" fields (& possibly others) are simply empty. Mauro wrote the function validateEmpty code above, but i can't get it to work. do i have it in the wrong placement within the script or doing something else wrong with it?
3b) it looks to me like this function is just for the "name" field, do i have to duplicate it for the "email" field?
PLEASE REMEMBER...
i want to be able to have a SIMPLE validation here as a fallback in case Javascript/Jquery isn't working for some reason.
also note that the above DOES "send" the email correctly; so am now just trying to get the validation & error message to work right.
thank you for your time & expertise!
tl;dr: both statements evaluate to true. It's better to return true or false instead of strings and handle the message later.
First I'll take care of your question, then I'll make some suggestions on good practices.
When you use return x; in PHP and most languages, you're "sending" x back to where you called the function. So, when your code is executed it will be read as:
if('ok')
or
if ('Error info...')
PHP evaluates the condition on an if statement (this is the part between parenthesis) as true or false by converting it to the boolean type. The string to boolean conversion in PHP is basically as follows: any non-empty string evaluates as TRUE (follow the link, check first table, last column).
So, your function is returning 'ok' if it succeeds, 'Error info...' if it fails, these are both non-empty strings and thereof evaluated as true, so no matter if the first email sending attempt went well, your script will try to send the second one, and will always set $msg to 'Email sent!'.
Here's some advice on how to fix your script so it works (and looks) better:
As #Matt suggested it's always best to validate the data by yourself instead of relying on PHPMailer to do so. Despite PHPMailer will return an error if the destination address is invalid, it's a good practice not to even call the library if the email is not valid. So:
First, validate the data using javascript, so your user get's instant feedback.
Then, validate it using PHP (maybe create a new validate() function that may use filter_var() to validate emails.
Last, send the email only if the previous two were successful.
To follow your chain of thought, you should be evaluating if the string returned by sendemail() equals to 'ok' or not:
if (sendemail(...) == 'ok')
But, instead of evaluating two different strings ('ok' or 'Error info...') it's better if the function returned boolean values instead, and since PHPMailer's send() already does, just keep it as you have it commented:
return $mail->send()
Your last line is using $mail, a variable that you declared inside a function and you never made global, so it won't be available at that point and since you're trying to get a property (ErrorInfo) you'll be firing two PHP notices: Undefined variable and Trying to get a property from a non-object. You COULD just add global $mail at the top of the function and that will make it globally available (outside your function's scope) but this is considered a bad practice since in large pieces of code you might get confused.
Instead, a neater way of firing the error would be to throw/catch an exception:
function sendemail(...) {
// ... PHPMailer config ...
if ($mail->send()) {
return true;
} else {
throw Exception('Error: ' + $mail->ErrorInfo);
}
}
// later...
try {
sendemail()
$msg = 'Email sent!';
} catch (Exception $e) {
$msg = 'Email failed!' . $e->getMessage();
}
Here, if there's a problem with the emails sending, your function will throw a generic exception and the catch part will be executed.
EVEN BETTER
If you initialize PHPMailer like this:
$mail = new PHPMailer(true); // note the parameter set to true.
It will throw an exception by itself if it fails to send the email and you'll be able to catch the exception:
function sendemail(...) {
$mail = PHPMailer(true); // this line
// ... PHPMailer config ...
return $mail->send(); // just to return something, we aren't really using this value anymore.
}
// later...
try {
sendemail(...)
$msg = 'Email sent!';
} catch (phpmailerException $e) {
echo $e->errorMessage(); // Catch PHPMailer exceptions (email sending failure)
} catch (Exception $e) {
echo $e->getMessage(); // Boring error messages from anything else!
}
Never forget to read the docs!

phpmailer Invalid Address Error

Code:
<?php
if(isset($_POST['data']) && !empty($_POST['data']) && isset($_POST['email']) && !empty($_POST['email'])) {
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
var_dump($email);
$data = explode(',', $_POST['data']);
mailImages($data);
}
function mailImages($data){
require_once "../PHPMailer_5.2.0/class.phpmailer.php";
$mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch
try {
$mail->CharSet = 'UTF-8';
$mail->AddReplyTo('kasper.lassner#peterwolf.agency', 'Colegio Suizo de México');
// $mail->AddAddress('******#****.agency','K L');
//$mail->AddAddress('"'.$email.'"','');
$mail->AddAddress($email,'test');
$mail->SetFrom('*******#********.agency', 'Colegio Suizo de México');
$mail->Subject = 'CSM Fotos';
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
$mail->MsgHTML('Test message');
foreach($data as $image){
$mail->AddAttachment(realpath(dirname(__FILE__)).'/'.str_replace(' ','',$image));
}
$mail->Send();
echo 'OK';
} catch (phpmailerException $e) {
//echo $e->errorMessage();
echo $mail->ErrorInfo;
} catch (Exception $e) {
echo 'NO';//Boring error messages from anything else!
}
}
?>
So my problem is the following: I get an "Invalid Address:"" Error. When I comment this line:
$mail->AddAddress($email,'test');
And uncomment this line:
$mail->AddAddress('******#****.agency','K L');
Passing a string value works. So the problem clearly is that the $email variable somehow isn't accepted. The var_dump outputs this: "string(24) "*******#****.com" so it is a string.
I've searched in already existing answers and couldn't find that specific issue.
Any help is greatly appreciated.
Your problem is explained in http://php.net/manual/en/language.variables.scope.php.
By default, every variable you use in a function is implicitly local to that function. The $email in mailImages is unrelated to the $email outside. Because the variable is not set, it causes the "Invalid Address" error.
You can fix this by either adding another function parameter:
function mailImages($data, $email) { ... }
// call as
mailImages($data, $email);
or by explicitly marking $email as global:
function mailImages($data) {
global $email;
...
}

Fatal error: Cannot redeclare PHPMailerAutoload()

I am using PHPMailer to send emails from my local host.
I have written a function which is supposed to send emails to registered users who have chosen the option to receive them. (i.e. newsletter subscription, etc)
function email_users($subject, $body) {
include('core/db/db_connection.php');
$sql = "SELECT email, first_name FROM `_users` WHERE allow_email = 1";
$query = mysqli_query($dbCon, $sql);
while (($row = mysqli_fetch_assoc($query)) !== false) {
$body = "Hello ". $row['first_name'] . ", <br><br>" . $body;
email($row['email'], $subject, $body);
}
}
The code that is calling the function:
if (isset($_GET['success']) === true && empty($_GET['success']) === true) {
?>
<h3 class="email_success">Emails have been sent</h2>
Go back to the admin page
<?php
} else {
if (empty($_POST) === false) {
if (empty($_POST['subject']) === true) {
$errors[] = 'A message subject is required.';
}
if (empty($_POST['body']) === true) {
$errors[] = 'A body message is required.';
}
if (empty($errors) === false) {
echo output_errors($errors);
} else {
email_users($_POST['subject'], $_POST['body']);
header('Location: email_users.php?success');
exit();
}
}
// generate email form otherwise
Any idea why I'm getting this error?
Fatal error: Cannot redeclare PHPMailerAutoload()
I would also like to point out that even with this error, the function still works and the emails are being sent...
EDIT: As requested, please see below the function using PHPMailer:
function email($user, $subject, $body) {
require 'phpmailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
/* $mail -> Host,username,password and other misc stuff
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AltBody = $body; etc */
}
If you use
require 'phpmailer/PHPMailerAutoload.php';
in your function, but you call the function 2 times, it will redeclare the class. Simply use require_once() instead.
require_once('phpmailer/PHPMailerAutoload.php');
After much testing, the solution I have found is adding the header redirect into the function and removing it from the calling code:
function email_users($subject, $body) {
include('core/db/db_connection.php');
$sql = "SELECT email, first_name FROM `_users` WHERE allow_email = 1";
$query = mysqli_query($dbCon, $sql);
while (($row = mysqli_fetch_assoc($query)) !== false) {
$body = "Hello ". $row['first_name'] . ", <br><br>" . $body;
email($row['email'], $subject, $body);
header('Location: email_users.php?success');
}
}
Also, as pointed out by honerlawd, require_once is needed in order for this to work, otherwise it will send an email only to the first account found in the database. Without redirecting to the email_users.php?success, this will cause an infinite loop, no matter if I call require_once or require.
Would this be the correct approach or is it just a temporary messy fix?

PHPMailerAutoload Completion Error

Edit: Jawish has explained why a blank page occurs when submitting my code. I simply forgot an echo statement. This has been marked as the correct answer even though it hasn't gotten my code to successfully run. My question was vague and Jawish found an issue that will help me with error reporting. I'll post another edit if I can find the issue with the code.
I'm having a small problem sending information using the following code to login to my gmail account. As soon as I run my form and submit it, I'm just shown a blank page. I've attempted to find some kind of error, but I can't get the error to display. I've followed the answer from this post, but even making those changes and adding the code does nothing that I can tell. This code is supposed to run the mailer and once the email is sent, the user is supposed to be redirected to a 'thank you' page with never happens. So the issue happens in one of the two codes listed. The strange thing is this use to work. I went on vacation then came back and now it doesn't work. I'm sure I messed something up somehow, but I'm at a loss for ideas.
Any help is appreciated, thanks. (asterisks are shown to hide personal information)
<?php
session_start();
require_once '../PHPMailer-master/PHPMailerAutoload.php';
if(isset($_POST['icon'])){
$m = new PHPMailer();
$m->isSMTP();
$m->SMTPAuth = true;
$m->Host = 'smtp.gmail.com';
$m->Username = '*********#gmail.com';
$m->Password = '****';
$m->SMTPSecure = 'ssl';
$m->Port = 465;
$m->isHTML(true);
$m->Subject = 'Contact form submitted';
$m->Body = $_POST['icon'];
$m->FromName = 'Contact';
$m->AddAddress('********#gmail.com','***Name Here****');
if($m->send()) {
header('Location: contact_thanks.php');
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $m->ErrorInfo;
die();
} else {
'Sorry, could not send email';
}
} else {'something went wrong';}
?>
This is the PHPMailerAutoload.php referenced in the previous code.
<?php
function PHPMailerAutoload($classname)
{
//Can't use __DIR__ as it's only in PHP 5.3+
$filename = dirname(__FILE__).DIRECTORY_SEPARATOR.'class.'.strtolower($classname).'.php';
if (is_readable($filename)) {
require $filename;
}
}
if (version_compare(PHP_VERSION, '5.1.2', '>=')) {
//SPL autoloading was introduced in PHP 5.1.2
if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
spl_autoload_register('PHPMailerAutoload', true, true);
} else {
spl_autoload_register('PHPMailerAutoload');
}
} else {
/**
* Fall back to traditional autoload for old PHP versions
* #param string $classname The name of the class to load
*/
function __autoload($classname)
{
PHPMailerAutoload($classname);
}
}
?>
You are missing "echo" statements on the last else blocks so you would not get any output on those branches.
Should be:
} else {
echo 'Sorry, could not send email';
}
} else {
echo 'something went wrong';
}

PHPMailer exception error

I've written my own Code Igniter model for sending emails. All was fine until recently when I started to get this error:
Fatal error: Cannot redeclare class phpmailerException in /home/mysite/public_html/subdir/application/libraries/phpmailer/class.phpmailer.php on line 2319
I'm using:
CodeIgniter 2
PHPMailer 5.1
I've tried the following to resolve it:
Added "$mail->SMTPDebug = 0" to turn off errors.
Added: "$mail->MailerDebug = false;"
Modified the PHPMailer to only show errors when SMTPDebug is turned on.
Looked for and removed any echo statements
Added try / catch blocks Tried adding / removing: $mail = new PHPMailer(true);
Here is my controller method (company/contact) which calls my model (message_model):
function contact()
{
//Do settings.
$this->options->task='email';
$this->options->change = 'sent';
$this->options->form_validation='';
$this->options->page_title='Contact Us';
//Import library
include_once('application/libraries/recaptcha/recaptchalib.php');//Include recaptcha library.
//Keys for recaptcha, stored in mainconfig file.
$this->options->publickey = $this->config->item('recaptcha_public');
$this->options->privatekey = $this->config->item('recaptcha_private');
//Form validation
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->form_validation->set_rules('name_field','Name of problem','trim|required|min_length[3]|max_length[100]');
$this->form_validation->set_rules('desc_field','Description','trim|required|min_length[10]|max_length[2000]');
$this->form_validation->set_rules('email_field','Your email address','trim|required|valid_email');
$this->form_validation->set_rules('recaptcha_response_field','captcha field','trim|required|callback__check_recaptcha');
//If valid.
if( $this->form_validation->run() )
{
//Set email contents.
$message="This is a message from the contact form on ".$this->config->item('site_name')."<br /><br />";
$message.=convert_nl($this->input->post('desc_field'));
$message.="<br /><br />Reply to this person by clicking this link: ".$this->input->post('name_field')."<br /><br />";
$options = array('host'=>$this->config->item('email_host'),//mail.fixilink.com
'username'=>$this->config->item('email_username'),
'password'=>$this->config->item('email_password'),
'from_name'=>$this->input->post('name_field'),
'to'=>array($this->config->item('email_to')=>$this->config->item('email_to') ),
'cc'=>$this->config->item('email_cc'),
'full_name'=>$this->input->post('name_field'),
'subject'=>'Email from '.$this->config->item('site_name').' visitor: '.$this->input->post('name_field'),
'message'=>$message,
'word_wrap'=>50,
'format'=>$this->config->item('email_format'),
'phpmailer_folder'=>$this->config->item('phpmailer_folder')
);
//Send email using own email class and phpmailer.
$result = $this->message_model->send_email($options);
//Second email to sender
//Set email contents.
$message="Thank you for your enquiry, we aim to get a reply to you within 2 working days. In the meantime, please do follow us on www.facebook.com/autismworksuk";
$options = array('host'=>$this->config->item('email_host'),//mail.fixilink.com
'username'=>$this->config->item('email_username'),
'password'=>$this->config->item('email_password'),
'from_name'=>$this->input->post('name_field'),
'to'=>$this->input->post('email_field'),
'full_name'=>$this->input->post('name_field'),
'subject'=>'Email from '.$this->config->item('site_name'),
'message'=>$message,
'word_wrap'=>50,
'format'=>$this->config->item('email_format'),
'phpmailer_folder'=>$this->config->item('phpmailer_folder')
);
//Send email using own email class and phpmailer.
$result = $this->message_model->send_email($options);
//Set result.
if($result==-1)
$this->session->set_flashdata('result', ucfirst($this->options->task).' was not '.$this->options->change.' because of a database error.');
elseif($result==0)
$this->session->set_flashdata('result', 'No changes were made.');
else
$this->session->set_flashdata('result', ucfirst($this->options->task).' was '.$this->options->change.' successfully.');
//Redirect to completed controller.
redirect('completed');
}
//Validation failed or first time through loop.
$this->load->view('company/contact_view.php',$this->options);
}
Here is my model's method to send the emails. It used to work but without any changes I can think of now I get an exception error:
function send_email($options=array())
{
if(!$this->_required(array('host','username','password','from_name','to','full_name','subject','message'),$options))//check the required options of email and pass aggainst provided $options.
return false;
$options = $this->_default(array('word_wrap'=>50,'format'=>'html','charset'=>'utf-8'),$options);
try
{
if(isset($options['phpmailer_folder']))
require($options['phpmailer_folder']."/class.phpmailer.php");
else
require("application/libraries/phpmailer/class.phpmailer.php");//Typical CI 2.1 folder.
$mail = new PHPMailer();
$mail->MailerDebug = false;
//Set main fields.
$mail->SetLanguage("en", 'phpmailer/language/');
$mail->IsSMTP();// set mailer to use SMTP
$mail->SMTPDebug = 0;
$mail->Host = $options['host'];
$mail->SMTPAuth = TRUE; // turn on SMTP authentication
$mail->Username = $options['username'];
$mail->Password = $options['password'];
$mail->FromName = $options['from_name'];//WHo is the email from.
$mail->WordWrap = $options['word_wrap'];// Set word wrap to 50 characters default.
$mail->Subject = $options['subject'];
$mail->Body = $options['message'];
$mail->CharSet = $options['charset'];
//From is the username on the server, not sender email.
if(isset($options['from']))
$mail->From = $options['from'];
else
$mail->From = $mail->Username; //Default From email same as smtp user
//Add reply to.
if(isset($options['reply_to']))
$mail->AddReplyTo($options['reply_to'], $options['from']);
if(isset($options['sender']))
$mail->Sender = $options['sender'];
//Add recipients / to field (required)
if(is_array($options['to']))
{
foreach($options['to'] as $to =>$fn)
$mail->AddAddress($to, $fn);
}
else
{
$mail->AddAddress($options['to']); //Email address where you wish to receive/collect those emails.
}
//Add cc to list if exists. Must be an array
if(isset($options['cc']))
{
if(is_array($options['cc']))
{
foreach($options['cc'] as $to =>$fn)
$mail->AddCC($to, $fn);
}
else
{
log_message('debug', '---->CC field must be an array for use with Message_Model.');
}
}
//Add bcc to list if exists. Must be an array
if(isset($options['bcc']))
{
if(is_array($options['bcc']))
{
foreach($options['bcc'] as $to =>$fn)
$mail->AddBCC($to, $fn);
}
else
{
log_message('debug', '---->BCC field must be an array for use with Message_Model.');
}
}
//Alternative text-only body.
if(isset($options['alt_body']))
$mail->AltBody=$options['alt_body'];
else
$mail->AltBody = htmlspecialchars_decode( strip_tags( $options['message'] ),ENT_QUOTES );//Strip out all html and other chars and convert to plain text.
//Plain/html format.
if(isset($options['format']))
{
if($options['format']=='html')
$mail->IsHTML(true); // set email format to HTML
}
//Send email and set result.
$return['message']='';
if(!$mail->Send())
{
$return['message'].= "Message could not be sent.<br />\n";
$return['message'].= "Mailer Error: " . $mail->ErrorInfo."\n";
$return['result'] = 0;
}
else
{
$return['message'].= "Message has been sent successfully.\n";
$return['result'] = 1;
}
}
catch (phpmailerException $e)
{
log_message('error', '---->PHPMailer error: '.$e->errorMessage() );
}
catch (Exception $e)
{
log_message('error', '---->PHPMailer error: '.$e->errorMessage() );
}
return $return;
}
if (!class_exists("phpmailer")) {
require_once('PHPMailer_5.2.2/class.phpmailer.php');
}
This Code will clear this issue 100%..
Basically one of two things is happening:
You are "including" your PHP code twice somewhere, causing the 2nd time to generate the redeclaration error
You are using "phpmailerException" somewhere else, besides your model. Have you tried to do a "find all" in your IDE for ALL calls to "phpmailerException" - perhaps you used this name in another area for another exception?
require_once("class.phpmailer.php") is better.
Mukesh is right that require_once will solve Sift Exchanges answer #1. However, there is not need to check if the class exists as require_once does that.

Categories