So I am using the PHPMailer library in PHP to send a welcome email when ever my users registered, and it takes so long to do this.
It takes around 30 - 50 seconds to actually load the home page, after clicking submit on the registration. It basically puts the page in a reloading state for over 30 seconds.
The code I use is below...
if ($config['user']['welcome_email_enabled'])
$autoLoader->getLibrary('mail')->sendWelcomeEmail($email, $username);
And my mail library is here.
<?php
/**
* MangoCMS, content management system.
*
* #info Handles the mail functions.
* #author Liam Digital <liamatzubbo#outlook.com>
* #version 1.0 BETA
* #package MangoCMS_Master
*
*/
defined("CAN_VIEW") or die('You do not have permission to view this file.');
class mangoMail {
private $phpMailer;
public function assignMailer($phpMailer) {
$this->phpMailer = $phpMailer;
}
public function setupMail($username, $password, $eHost) {
if ($this->phpMailer == null)
return;
$this->phpMailer->isSMTP();
$this->phpMailer->Host = $eHost;
$this->phpMailer->SMTPAuth = true;
$this->phpMailer->Username = $username;
$this->phpMailer->Password = $password;
$this->phpMailer->SMTPSecure = 'tls';
$this->phpMailer->Port = 587;
}
public function sendMail() {
if ($this->phpMailer == null)
return;
if (!$this->phpMailer->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $this->phpMailer->ErrorInfo;
exit();
}
else {
echo 'Email has been sent.';
}
}
public function setFrom($from, $fromTitle) {
$this->phpMailer->setFrom($from, $fromTitle);
}
public function addAddress($address) {
$this->phpMailer->addAddress($address);
}
public function setSubject($subject) {
$this->phpMailer->Subject = $subject;
}
public function setBody($body) {
$this->phpMailer->Body = $body;
}
public function setAltBody($altBody) {
$this->phpMailer->AltBody = $altBody;
}
public function setHTML($html) {
$this->phpMailer->isHTML($html);
}
public function addReply($email, $name = '') {
$this->phpMailer->addReplyTo($email, $name);
}
public function sendWelcomeEmail($email, $username) {
global $config;
$mailer = $this->phpMailer;
$mailer->setFrom($config['website']['email'], $config['website']['owner']);
$mailer->addAddress($email, $username);
$mailer->addReplyTo($config['website']['email'], 'Reply Here');
$mailer->isHTML(true);
$mailer->Subject = 'Welcome to ' . $config['website']['name'] . ' (' . $config['website']['link'] . ')';
$mailer->Body = '<div style="background-color:#1a8cff;padding:24px;color:#fff;border-radius:3px;">
<h2>Welcome to Zubbo ' . $username . '!</h2>Thank you for joining the Zubbo community, we offer spectacular events, opportunities, and entertainment.<br><br>When you join Zubbo you will recieve <b>250,000 credits</b>, <b>100,000 duckets</b>, and <b>5 diamonds</b>. One way to earn more is by being online and active, the more you are active the more you will earn, other ways are competitions, events, and games :)<br><br>We strive to keep the community safe and secure, so if you have any questions or concerns or have found a bug please reply to this email or contact us using in-game support.<br><br>Thank you for joining Zubbo Hotel!<br>- Zubbo Staff Team
</div>';
$mailer->AltBody = 'Here is a alt body...';
if (!$mailer->send()) {
exit('FAILED TO SEND WELCOME EMAIL!! ' . $mailer->ErrorInfo);
}
}
}
?>
So I call these to start with, then the sendWelcomeEmail() when I want to actually send the email.
$mailer->assignMailer(new PHPMailer());
and
$mailer->setupMail(
"********#gmail.com",
"**************",
"smtp.gmail.com");
Why is it taking so long? Should it be taking this long..
Remote SMTP is not really a good thing to use during page submissions - it's often very slow (sometimes deliberately, for greetdelay checks), as you're seeing. The way around it is to always submit to a local (fast) mail server and let it deal with the waiting around, and also handle things like deferred delivery which you can't handle from PHPMailer. You also need to deal with bounces correctly when going that route as you won't get immediate feedback.
That you can often get away with direct delivery doesn't mean it's a reliable approach.
To see what part of the SMTP conversation is taking a long time, set $mailer->SMTPDebug = 2; and watch the output (though don't do that on your live site!).
Don't know if PHPMailer is compulsory for you or not, but if it's not I am recommanding SwiftMailer .
as per my personal Experience It's Really fast and reliable.
Thanks.
include_once "inc/swift_required.php";
$subject = 'Hello from Jeet Patel, PHP!'; //this will Subject
$from = array('jeet#mydomain.com' =>'mydomain.com'); //you can use variable
$text = "This is TEXT PART";
$html = "<em>This IS <strong>HTML</strong></em>";
$transport = Swift_SmtpTransport::newInstance('abc.xyz.com', 465, 'ssl');
$transport->setUsername('MYUSERNAME#MYDOMAIN.COM');
$transport->setPassword('*********');
$swift = Swift_Mailer::newInstance($transport);
$to = array($row['email'] => $row['cname']);
$message = new Swift_Message($subject);
$message->setFrom($from);
$message->setBody($html, 'text/html');
$message->setTo($to);
$message->addPart($text, 'text/plain');
if ($swift->send($message, $failures))
{
echo "Send successfulllyy";
} else {
print_r($failures);
}
Related
I need assistance with sending bulk email.
This is this scanario.
A dropdown contains the categories of emails to be fetched. The selected (value) is then passed through a function that obtains all the emails per the selected value from db. And the emails passed to the mailer's addAddress method.
The sql query works fine but my headers show only the selected value from the network session and not all the returned emails. I am including both php codes and the ajax codes and also the response headers.
PHP block
$accountid = $_POST['accountid'];
$selectedstatus = $_POST['bulkrecipients']; //From dropdown
$emailtype = $_POST['emailtype'];
$subject = sanitize_text($_POST['bulksubject']);
$message = sanitize_text($_POST['bulkmessage']);
//Pass recipientemails to function and extract individual emails.
$getemails = getAllEmailsFromStatus($selectedstatus , $_SESSION['username']);
$name = 'Tester';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPKeepAlive = true;
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = "";
$mail->Password = '';
$mail->Port = 465;
$mail->SMTPSecure = "ssl";
$mail->isHTML(true);
$mail->setFrom('testproject222', $name);
$mail->Subject = ("$subject");
$mail->Body = $message;
foreach ($getemails as $row) {
try {
$mail->addAddress($row['email']);
} catch (Exception $ex) {
echo 'Invalid address skipped: ' . htmlspecialchars($row['email']) . '<br>';
continue;
}
try {
if ($mail->send()) {
$status = "success";
$response = "Email is sent";
//Save the contact details to db.
saveAllEmployerEmails($accountid , $subject, emailtype, $message );
} else {
$status = "failed";
$response = 'Something is wrong ' . $mail->ErrorInfo;
}
exit(json_encode(array("status" => $status, "response" => $response)));
} catch (Exception $ex) {
echo 'Mailer Error (' . htmlspecialchars($row['email']) . ') ' . $mail->ErrorInfo . '<br>';
$mail->getSMTPInstance()->reset();
}
$mail->clearAddresses();
$mail->clearAttachments();
}
Ajax
function sendBulk() {
var url = "./inc/emailjobs.php";
var accountid = $("#accountid");
var emailtype = $("#emailtype");
var recipientemails = $("#bulkrecipients");
var bulksubject = $("#bulksubject");
var bulkmessage = $('#' + 'bulkmessage').html( tinymce.get('bulkmessage').getContent() );
if (isNotEmpty(recipientemails) /*&& isNotEmptyTextArea("bulkmessage")*/) {
$.ajax({
url: url,
method: 'POST',
cache: false,
dataType: 'json',
beforeSend: function () {
$('#bulksendbtn').text("Sending...");
},
data: {
accountid: accountid.val(),
emailtype: emailtype.val(),
bulksubject: bulksubject.val(),
bulkrecipients: recipientemails.val(),
bulkmessage: bulkmessage.val()
}
, success: function (response) {
$('#bulkemailForm')[0].reset();
$('.bulksendmessage').text("Emails Sent.");
$('#bulksendbtn').text("Sent");
},
});
}
}
Response Form header data
accountid: 2
emailtype: bulk
bulksubject: Test
bulkrecipients: shortlisted
bulkmessage: <p>Testing... </p>
Instead of the 'shortlisted' for bulkrecipients, I expect the email addresses. I was hoping to see 2 returned emails. The 'shortlisted' is supposed to be used to obtain the emails for that category (shortlisted).
Your code looks generally correct, but this is confusing:
$mail->setFrom('Test', $name);
//$mail->From = ("$email");
$email isn't defined, and Test is not a valid from address. I have a suspicion you're trying to use an arbitrary user-submitted email address as the from address. That will not work with Gmail because Gmail does not allow setting arbitrary from addresses; it will only let you send as the account owner (what you put in Username), or aliases that you preset in gmail settings. If you try to use anything else, it will simply ignore it and use your account address instead. Is this what you meant by "only the selected value from the network session"?
It's entirely reasonable for gmail to do this since almost by definition anything other than your account address is likely to be forgery, and nobody likes that.
If you want to send email where replies will go to a user-submitted address, use your own address in the from address, and use the user-submitted address as a reply-to. See the contact form example provided with PHPMailer for how to do that.
I am using PHPMailer to send email to my clients. But I am not satisfied with the output of the
I want to remove <michael#gmail.com> at the end of my name but not sure how to do it.
My current script:
$mail->SetFrom("michael#gmail.com",'Michael Chu');
$mail->XMailer = 'Microsoft Mailer';
$mail->AddAddress($email);
$mail->Subject = "TEST Email";
$mail->Body = "<p>TEST Email<p>";
The relevant parts in the PHPMailer code is in the Pre Send routine, which assembles the mail (and which is obviously called internally always before send):
public function preSend() {
...
try {
$this->error_count = 0; // Reset errors
$this->mailHeader = '';
...
// Create body before headers in case body makes changes to headers (e.g. altering transfer encoding)
$this->MIMEHeader = '';
$this->MIMEBody = $this->createBody();
// createBody may have added some headers, so retain them
$tempheaders = $this->MIMEHeader;
$this->MIMEHeader = $this->createHeader();
$this->MIMEHeader .= $tempheaders;
...
return true;
This will be called always. Now: when we look at the createHeader-function we see this:
public function createHeader()
{
$result = '';
...
$result .= $this->addrAppend('From', [[trim($this->From), $this->FromName]]);
...
return $result;
}
So: Create Header always adds the From Address part, but it relies on addrAppend to format it (passing 'From' and an array containing one address-array [email, name])
public function addrAppend($type, $addr)
{
$addresses = [];
foreach ($addr as $address) {
$addresses[] = $this->addrFormat($address);
}
return $type . ': ' . implode(', ', $addresses) . static::$LE;
}
The address-array is passed on:
public function addrFormat($addr)
{
if (empty($addr[1])) { // No name provided
return $this->secureHeader($addr[0]);
}
return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') .
' <' .
$this->secureHeader($addr[0])
. '>';
}
and formatted with the email... Nothing you can do about it.
So with phpmailer you can't do it. But you can write your own subclass.
Probably something along those lines
<?php
//Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require '../vendor/autoload.php';
/**
* Use PHPMailer as a base class and extend it
*/
class myPHPMailer extends PHPMailer
{
public function addrFormat($addr)
{
if (empty($addr[1])) { // No name provided
return $this->secureHeader($addr[0]);
}
else {
return $this->secureHeader($addr[1]);
}
}
}
So I am using the PHPMailer library in PHP to send a welcome email when ever my users registered, and it takes so long to do this.
It takes around 30 - 50 seconds to actually load the home page, after clicking submit on the registration. It basically puts the page in a reloading state for over 30 seconds.
The code I use is below...
if ($config['user']['welcome_email_enabled'])
$autoLoader->getLibrary('mail')->sendWelcomeEmail($email, $username);
And my mail library is here.
<?php
/**
* MangoCMS, content management system.
*
* #info Handles the mail functions.
* #author Liam Digital <liamatzubbo#outlook.com>
* #version 1.0 BETA
* #package MangoCMS_Master
*
*/
defined("CAN_VIEW") or die('You do not have permission to view this file.');
class mangoMail {
private $phpMailer;
public function assignMailer($phpMailer) {
$this->phpMailer = $phpMailer;
}
public function setupMail($username, $password, $eHost) {
if ($this->phpMailer == null)
return;
$this->phpMailer->isSMTP();
$this->phpMailer->Host = $eHost;
$this->phpMailer->SMTPAuth = true;
$this->phpMailer->Username = $username;
$this->phpMailer->Password = $password;
$this->phpMailer->SMTPSecure = 'tls';
$this->phpMailer->Port = 587;
}
public function sendMail() {
if ($this->phpMailer == null)
return;
if (!$this->phpMailer->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $this->phpMailer->ErrorInfo;
exit();
}
else {
echo 'Email has been sent.';
}
}
public function setFrom($from, $fromTitle) {
$this->phpMailer->setFrom($from, $fromTitle);
}
public function addAddress($address) {
$this->phpMailer->addAddress($address);
}
public function setSubject($subject) {
$this->phpMailer->Subject = $subject;
}
public function setBody($body) {
$this->phpMailer->Body = $body;
}
public function setAltBody($altBody) {
$this->phpMailer->AltBody = $altBody;
}
public function setHTML($html) {
$this->phpMailer->isHTML($html);
}
public function addReply($email, $name = '') {
$this->phpMailer->addReplyTo($email, $name);
}
public function sendWelcomeEmail($email, $username) {
global $config;
$mailer = $this->phpMailer;
$mailer->setFrom($config['website']['email'], $config['website']['owner']);
$mailer->addAddress($email, $username);
$mailer->addReplyTo($config['website']['email'], 'Reply Here');
$mailer->isHTML(true);
$mailer->Subject = 'Welcome to ' . $config['website']['name'] . ' (' . $config['website']['link'] . ')';
$mailer->Body = '<div style="background-color:#1a8cff;padding:24px;color:#fff;border-radius:3px;">
<h2>Welcome to Zubbo ' . $username . '!</h2>Thank you for joining the Zubbo community, we offer spectacular events, opportunities, and entertainment.<br><br>When you join Zubbo you will recieve <b>250,000 credits</b>, <b>100,000 duckets</b>, and <b>5 diamonds</b>. One way to earn more is by being online and active, the more you are active the more you will earn, other ways are competitions, events, and games :)<br><br>We strive to keep the community safe and secure, so if you have any questions or concerns or have found a bug please reply to this email or contact us using in-game support.<br><br>Thank you for joining Zubbo Hotel!<br>- Zubbo Staff Team
</div>';
$mailer->AltBody = 'Here is a alt body...';
if (!$mailer->send()) {
exit('FAILED TO SEND WELCOME EMAIL!! ' . $mailer->ErrorInfo);
}
}
}
?>
So I call these to start with, then the sendWelcomeEmail() when I want to actually send the email.
$mailer->assignMailer(new PHPMailer());
and
$mailer->setupMail(
"********#gmail.com",
"**************",
"smtp.gmail.com");
Why is it taking so long? Should it be taking this long..
Remote SMTP is not really a good thing to use during page submissions - it's often very slow (sometimes deliberately, for greetdelay checks), as you're seeing. The way around it is to always submit to a local (fast) mail server and let it deal with the waiting around, and also handle things like deferred delivery which you can't handle from PHPMailer. You also need to deal with bounces correctly when going that route as you won't get immediate feedback.
That you can often get away with direct delivery doesn't mean it's a reliable approach.
To see what part of the SMTP conversation is taking a long time, set $mailer->SMTPDebug = 2; and watch the output (though don't do that on your live site!).
Don't know if PHPMailer is compulsory for you or not, but if it's not I am recommanding SwiftMailer .
as per my personal Experience It's Really fast and reliable.
Thanks.
include_once "inc/swift_required.php";
$subject = 'Hello from Jeet Patel, PHP!'; //this will Subject
$from = array('jeet#mydomain.com' =>'mydomain.com'); //you can use variable
$text = "This is TEXT PART";
$html = "<em>This IS <strong>HTML</strong></em>";
$transport = Swift_SmtpTransport::newInstance('abc.xyz.com', 465, 'ssl');
$transport->setUsername('MYUSERNAME#MYDOMAIN.COM');
$transport->setPassword('*********');
$swift = Swift_Mailer::newInstance($transport);
$to = array($row['email'] => $row['cname']);
$message = new Swift_Message($subject);
$message->setFrom($from);
$message->setBody($html, 'text/html');
$message->setTo($to);
$message->addPart($text, 'text/plain');
if ($swift->send($message, $failures))
{
echo "Send successfulllyy";
} else {
print_r($failures);
}
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.
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.