phpmailer causing Cross-Origin Request Blocked on Hosting - php

I'm newbie mobile developer, I'm using phonegap as my framework also I'm using firebug to ease me looking for the error / bug that I've got.
I got this error (that I've got on firebug) :
Cross-Origin Request Blocked: The Same Origin Policy disallows.....
This is my code (on server side, because maybe the culprit is the phpmailer and the ajax) :
PHPMailer :
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: X-Requested-With");
header("Content-Type: text/html; charset=UTF-8");
include 'db_connect.php';
$applicantEmail = $_POST['PHPRequestor'];
$forgottenPass = '';
//for checking email
$q = "SELECT * FROM user WHERE email = '".$applicantEmail."'";
$result = mysqli_query($con, $q);
if ($result->num_rows == 0) {
echo "no email";
} else if ($result->num_rows == 1) {
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$forgottenPass = $row["pw"];
}
require_once ('class_email/PHPMailerAutoload.php'); //include library phpmailer using auto load
/*
require_once 'class_email/class.phpmailer.php';
require_once 'class_email/class.smtp.php';
*/
$mail = new PHPMailer();
$body =
"<body style='margin: 5px;'>
<br/>
<strong> 'Forgot Password' </strong> :
<br/>
<div style='width: 320px; border:#000000 solid 2px;'>
Your pass : <strong> ".$forgottenPass." </strong> <br/>
</div>
<br/>
Thanks
<br/>
</body>";
$body = eregi_replace("[\]",'',$body);
$mail->IsSMTP(); //Using SMTP
//Activated debug SMTP to see http response
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
//$mail->SMTPDebug = 2;
$mail->SMTPAuth = true; //Authentication
$mail->SMTPSecure = "tls";
// sets the prefix to the
$mail->Host = "smtp.gmail.com"; //Set GMAIL as the SMTP
$mail->Port = 587; //Set the SMTP port for the GMAIL server
$mail->Username = "myemail#email.com"; //Email
$mail->Password = "thepassword"; //Password
//This will add 'Your Name' to the from address, so that the recipient will know the name of the person who sent the e-mail.
$mail->SetFrom("myemail#email.com", "Request Forgot Password");
$mail->AddReplyTo("myemail#email.com", "Request Forgot Password");
$mail->Subject = "Request Forgot Password', user : ".$applicantEmail;
$mail->MsgHTML($body);
$address = "targetemail#email.com"; //target email
$mail->AddAddress($address, "'Permintaan Lupa kata sandi'");
if($mail->Send()) {
echo "success";
} else {
echo "Oops, Mailer Error: " . $mail->ErrorInfo;
exit;
}
}
$con->close();
?>
Ajax (using jquery)
function sendForgotPassword(FPEmail) {
var requestor = FPEmail;
//create form_data for post data on ajax PHP
var form_data = new FormData();
form_data.append("PHPRequestor", requestor);
$.ajax ({
type: "POST",
url: to_phpSide,
data: form_data,
contentType : false,
processData : false,
beforeSend: function() {
loadingPageW(1);
},
success: function(data){
if (data == 'success') {
//when success
} else if (data == 'no email') {
//when no email
} else {
//when error or something else occured
}
}, //for error message
error: function (xhr, errorStats, errorMsg) {
alert("error: "+xhr.errorStats+" , "+errorMsg);
},
complete: function() {
loadingPageW(2);
}
});
};
I already tried in localhost and work well.
But when I trying on hosting, I've got error (on top).
I'm really curious, if the error because of my page trying to request something that cross domain,
then why on the other pages (that I using same method, but without phpmailer) work nice on hosting?
Is there something error? Or method that I miss?
FYI :
I already check about SMTP (phpmailer) support on my hosting and that's support well.
I'm not place the html page in hosting, I just place the .php in hosting
Also I already try : How to specify the SMTP server in PHPMailer?
But still not a chance.
Thanks,
Any help would be appreciate :)
-Edit :
On my firebug (console) there's no error that I got, I already activated $mail->SMTPDebug = 2;, but I couldn't see the error or something else, the response is just empty (nothing there)
I just see
Cross-Origin Request Blocked: The Same Origin Policy disallows.....
-Edit 2 :
By the request #synchro about the URL that causing the error, below is the full error :
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at http:// myhost/www/myphp. This can be fixed by
moving the resource to the same domain or enabling CORS.
note :
myhost is refer to page that I used for hosting.
myphp is the .php file that contain code above (PHPMailer code)

If you serve your page from http://localhost/index.php and it talks to http://somewhereelse/index.php, that's cross-origin because the domains do not match. You can solve that in several ways:
Set access-control headers as others have described
Proxy the request on your own server so it doesn't appear cross-origin to the browser.
Do whatever it is that the target script does on your own server
The last of these is the simplest.
Also it looks like you're using an old version of PHPMailer and have based your code on an old example. Get the latest here, and look at the examples and wiki.

Try using this code in your PHPMailer:
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

Related

Send bulk message using php mailer with ajax

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.

PhpMailer doesn't send Email with .pdf file attached

I want to send a file via PhpMailer. If the file has extension .txt or .png ecc.. It sends me the email with the file (it works) but if I want to send a .pdf I don't receive the email ... this is a part of my PHP code:
$Name = $_POST['Name'];
$Email = $_POST['Email'];
$Surname = $_POST['Surname'];
$Residence = $_POST['Residence'];
$Phone = $_POST['Phone'];
$Name = filter_var($Name, FILTER_SANITIZE_STRING);
$Surname = filter_var($Surname, FILTER_SANITIZE_STRING);
$Email = filter_var($Email, FILTER_SANITIZE_EMAIL);
$Residence = filter_var($Residence, FILTER_SANITIZE_STRING);;
$Phone = filter_var($Phone, FILTER_SANITIZE_STRING);;
$mail = new PHPMailer();
$mail->SMTPAuth = true;
$mail->Host = "smtp.gmail.com"; // SMTP server
$mail->SMTPSecure = "ssl";
$mail->Username = "xxx"; //account with which you want to send mail. Or use this account. i dont care :-P
$mail->Password = "xxx"; //this account's password.
$mail->SetFrom('xxx');
$mail->Port = "465";
$mail->isSMTP(); // telling the class to use SMTP
$rec1="xxx"; //receiver. email addresses to which u want to send the mail.
$mail->AddAddress($rec1);
$mail->Subject = "Eventbook";
$mail->isHTML(true);
$mail->Body = "<h1>Contact from Website</h1>
<ul>
<li>Nome: {$Name}</li>
<li>Cognome: {$Surname}</li>
<li>Comune di residenza: {$Residence}</li>
<li>Email: {$Email}</li>
<li>Telefono: {$Phone}</li>
</ul>";
$mail->WordWrap = 200;
$mail->addAttachment($_FILES['curriculum']['tmp_name'], $_FILES['curriculum']['name']);
if(!$mail->Send()) {
echo 'Message was not sent!.';
$errore = $mail->ErrorInfo;
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo //Fill in the document.location thing
'<script type="text/javascript">
if(confirm("Your mail has been sent"))
document.location = "/";
</script>';
}
This is the JS script with ajax:
var formData = new FormData();
formData.append('Name', $('#Name').val());
formData.append('Surname', $('#Surname').val());
formData.append('Residence', $('#Residence').val());
formData.append('Email', $('#Email').val());
formData.append('Phone', $('#Phone').val());
formData.append('Curriculum', $('#Curriculum')[0].files[0]);
$.ajax({
method: 'POST',
url: "scripts/register.php",
data: formData,
processData: false,
contentType: false,
success: function (Curriculum) {
alert('Success');
}
});
This is the HTML file input part:
<input type="file" name="Curriculum" id="Curriculum" style="display: none;" class="form__input" />
<label for="Curriculum" id="LabelCurriculum" class="form__input" style="background-color: white; display: block; width: 100%; padding: 20px; font-family: Roboto; -webkit-appearance: none; border: 0; outline: 0; transition: 0.3s;">Click to upload</label>
It seems that It can't upload due to its size maybe ... because I uploaded .txt and .png of 50KB but the .pdf is 1MB
UPDATE: When I debug I can see that the file is uploaded , so I think that it don't send the email... why????
Don't use values directly from the $_FILES superglobal as they are potentially forgeable. You must validate them using the built-in move_uploaded_file or is_uploaded_file functions. The PHP docs on handling file uploads are excellent, so do what they say.
Base your code on the send file upload example provided with PHPMailer which uses move_uploaded_file before using the file. It's also a good idea to not use user-supplied filenames so as to avoid the possibility of file overwrite attacks - in the example you'll see it uses a hash of the filename (which will always be safe) to avoid doing that.
It's a good idea to check return values from critical functions - addAttachment() returns false if it can't read the file you ask it to read, for example:
if (!$mail->addAttachment($filename, 'file.pdf')) die('Could not read file!');
Look at the file upload size limit set in your PHP config, and mirror that in your form - see here and here. If you exceed this limit, you may find that you still have an entry in your $_FILES array, but it may point to an empty or non-existent file, which is another reason to validate and check return values. You can var_dump($_FILES) to see exactly what your script is receiving - it may not contain what you think it should.
I can see that you've based your code on a very old example, so make sure you're running the latest version of PHPMailer too.

PHP 7.0 STRPOS not functioning as expected

So, I was trying to use strpos to test if a string existed in a variable, but in all my attempts to make the if statement work, it was not succeeding, so I went about outputting the string and trying to find the point where strpos detected it, but it was not though it was clearly there! In this case I am searching an SMTP error output for the Gmail SMTP error code.I know how to fix the error, but I want my system to be able to parse smtp errors and report them to my users...
PHP Code:
$Request = RequestPasswordReset($_POST["email"]);
echo $Request;
echo "<br>Position of Error Code: " . strpos($Request, "gsmtp SMTP code: 550");
die();
if($Request === "SUCCESS") {
DisplayError("Password Reset Successful", "We have sent a email that contains a link to reset your password.", "/account/resetpassword.php");
} else if($Request === "USER_NOT_FOUND") {
DisplayError("Password Reset Request Failed", "The specified email is not tied to any accounts in our system.", "/account/resetpassword.php");
} else if(strpos($Request, "gsmtp SMTP code: 550") !== false) {
DisplayError("Password Reset Request Failed", "The mail was blocked by our relay due to IPs being not whitelisted.", "/account/resetpassword.php");
} else {
DisplayError("Password Reset Request Failed", "The request failed for an unknown reason.", "/account/resetpassword.php");
}
Text Output:
It does actually repeat itself, I echoed out the $Request twice and it did the following twice exactly
The following From address failed: XXXXXXX : MAIL FROM command failed,Invalid credentials for relay [XXXXXXX]. The IP address you've registered in your G Suite SMTP Relay service doesn't match domain of the account this email is being sent from. If you are trying to relay mail from a domain that isn't registered under your G Suite account or has empty envelope-from, you must configure your mail server either to use SMTP AUTH to identify the sending domain or to present one of your domain names in the HELO or EHLO command. For more information, please visit https://support.google.com/a/answer/6140680#invalidcred r126sm1314271qke.4 - gsmtp ,550,5.7.1SMTP server error: MAIL FROM command failed Detail: Invalid credentials for relay [XXXXXXX]. The IP address you've registered in your G Suite SMTP Relay service doesn't match domain of the account this email is being sent from. If you are trying to relay mail from a domain that isn't registered under your G Suite account or has empty envelope-from, you must configure your mail server either to use SMTP AUTH to identify the sending domain or to present one of your domain names in the HELO or EHLO command. For more information, please visit https://support.google.com/a/answer/6140680#invalidcred r126sm1314271qke.4 - gsmtp SMTP code: 550 Additional SMTP info: 5.7.1Position of Error Code:
(EDIT) Reset Password Request Function:
function RequestPasswordReset($Email) {
// Try to Get User
$User = GetUser_Email($Email);
// Does user exist?
if($User === "NOT_FOUND") {
return "USER_NOT_FOUND";
}
// Generate Link To Send with Email
$Link = GeneratePasswordResetLink();
$SendEmail = SendPasswordReset($User["Email"], $User["FirstName"] . $User["LastName"], $Link);
if($SendEmail !== "SUCCESS") {
return $SendEmail;
} else {
// WHAT IF MYSQL FAILS????? ~~~~~~~~~~~~~~~ NEED SOLOUTION
$PDO_Connection = CreateMySQLConnection();
$PDO_CMD = $PDO_Connection -> prepare("UPDATE accounts SET ResetPassword=? WHERE Email=?");
$PDO_CMD -> execute(array($Link, $User["Email"]));
return "SUCCESS";
}
}
(EDIT) Send Password Reset Function:
$User = GetUser_ResetID($resetID);
$mail = CreateSMTPConnection();
$mail->AddAddress($targetAddress, $targetName); // Add a recipient
$mail->IsHTML(true); // Set email format to HTML
$mail->Subject = 'LitenUp Password Reset';
$mail->Body = str_replace("https://mylitenup.net/account/resetpassword.php?ID=", ("https://mylitenup.net/account/resetpassword.php?ID=" . $resetID), file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/php/mailer/documents/resetpassword.html"));
$mail->AltBody = 'Reset Your Password: https://mylitenup.net/account/resetpassword.php?ID=' . $resetID;
$mail->XMailer = 'LitenUp Mailer';
$mail->XPriority = '1';
try{
$mail->send();
return "SUCCESS";
} catch (phpmailerException $e) {
return $e->errorMessage();
} catch (\Exception $e) {
return $e->getMessage();
}
(EDIT): I tried mb_strpos, but it is not working, so if that is what will work, why is it not working for me? I did mb_strpos($Request, "gsmtp SMTP code: 550");, but after execution it echos the request, but the Position of Error Code: line does not get echoed.
(Update 1): I really apologize for the delay, in a worst case I will extend this again with a bounty. However, you guys were right! When I first had the error, I outputted it and just copied the line "gsmtp SMTP code: 550", but after doing the tag there appears to be a new line of some sort. You can see in the that the line should be something more like "gsmtp" + + " SMTP code: 550", but I am not sure what the line break should be. I tried and \n.
The best solution would be to take the time to isolate exactly what character(s) is in that white-space.
Until you do that, you can just use regex to gloss over whatever is in there.
Change:
} else if(strpos($Request, "gsmtp SMTP code: 550") !== false) {
to:
} elseif(preg_match("/gsmtp\s+SMTP\s+code:\s+550/",$Request)) {
My best guess:
You're outputting to HTML, so it's possible that your CRLFs/LFs are rendering as spaces. I'd enclose your echo statements with <pre>...</pre> tags to see if it's the case. strpos would fail because you're searching for a space character where it's actually a CRLF/LF.

Can not send email threw SwiftMailer with Mandrill

Since today, many of my php applications can not send email using SwiftMailer and different Mandrill accounts.
I've got this code, and the send function in the last if stop the script..
// Instance message
$message = Swift_Message::newInstance();
$message->setSubject("subject")
->setFrom(array('noreply#email.test' => 'test'))
->setTo(array('a_valid_email' => 'name'))
->setBody("test", 'text/html')
->setPriority(2);
$smtp_host = 'smtp.mandrillapp.com';
$smtp_port = 587;
$smtp_username = 'valid_username';
$smtp_password = 'valid_password';
// SMTP
$smtp_param = Swift_SmtpTransport::newInstance($smtp_host , $smtp_port)
->setUsername($smtp_username)
->setPassword($smtp_password);
// Instance Swiftmailer
$instance_swiftmailer = Swift_Mailer::newInstance($smtp_param);
$type = $message->getHeaders()->get('Content-Type');
$type->setValue('text/html');
$type->setParameter('charset', 'iso-8859-1');
//Here the send function stop event and I did not go inside the if
if ($instance_swiftmailer->send($message, $fail)) {
echo 'OK ';
}else{
echo 'NOT OK : ';
print_r($fail);
}
Thank you in advance to help me to solve this problem..
If your code used to work, and now doesn't work, and you didn't change your code, then it's probably not a problem with your code. Check your Mandrill account validity - sometimes they suspend accounts for suspicious-appearing usage.

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