Fatal error: Cannot redeclare PHPMailerAutoload() - php

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?

Related

cryptic mail body when using imap_fetchbody

I am using following code to exctract among others the mail body of mails.
$imap = imap_open($mailbox,$user,$password);
$mails = imap_search($imap,'UNSEEN');
foreach($mails as $mail)
{
$message = trim(utf8_encode(quoted_printable_decode(imap_fetchbody($imap,$mail,"1"))));
if(strpos($message,"<html") !== false)
{
$mail_body = fopen($dir."mail.html","w");
}
else
{
$mail_body = fopen($dir."mail.txt","w");
}
}
This is working fine and it works with every test I did.
html-mails, plain-text-mails, also if the mails are forwarded.
Now from some other source I get mails, where the message (after using imap_fetchbody) just looks like some crypted string. Like this:
dGVpZW4gaW0gUERGLUZvcm1hdDoNClJla2xhbWF0aW9uc2luZm9ybWF0aW9uOiAyMTMzNjc0MSBS
SV8yMTMzNjc0MS5wZGYNCg0KTWl0IGZyZXVuZGxpY2hlbiBHcsO8w59lbg0KSWhyIG5vYmlsaWEg
VGVhbQ0KX19fDQoNCm5vYmlsaWEtV2Vya2UgSi4gU3RpY2tsaW5nIEdtYkggJiBDby4gS0cgfCBX
YWxkc3RyLiA1My01NyB8IDMzNDE1IFZlcmwNCg0KRGllIEdlc2VsbHNjaGFmdCBpc3QgZWluZSBL
I already tried to use some other arguments for imap_fetchbody like "1.1" or "1.2", but when I do that the message is empty.
Do you have any idea why this effect occurs?
I finally found a solution. The cause seems to be forwarded mails, that were initially sent from an apple device.
Now I use this to extract the message and it works.
$structure = imap_fetchstructure($imap, $mail);
$part = $structure->parts[1];
$message = imap_fetchbody($imap,$mail,1);
if(strpos($message,"<html") !== false)
{
$message = trim(utf8_encode(quoted_printable_decode($message)));
}
else if($part->encoding == 3)
{
$message = imap_base64($message);
}
else if($part->encoding == 2)
{
$message = imap_binary($message);
}
else if($part->encoding == 1)
{
$message = imap_8bit($message);
}
else
{
$message = trim(utf8_encode(quoted_printable_decode(imap_qprint($message))));
}

PHP Mailer taking over 30 seconds to send a welcome email

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);
}

PHPMailer send() function taking a long time [duplicate]

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);
}

Confirmation code wont copy to phpmailer

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.

Creating a Craigslist Anonymous Email Forwarding Program

The following program is intended to match incoming email aliases with those in the database, and forward the email to the right address, like Craigslist does.
I am now getting this error:
Error: [1] You must provide at least one recipient email address.
in anon-email.php at line number: sending the email
Here is the code:
$mailboxinfo = imap_mailboxmsginfo($connection);
$messageCount = $mailboxinfo->Nmsgs; //Number of emails in the inbox
for ($MID = 1; $MID <= $messageCount; $MID++)
{
$EmailHeaders = imap_headerinfo($connection, $MID); //Save all of the header information
$Body = imap_qprint(imap_fetchbody($connection, $MID, 1)); //The body of the email to be forwarded
$MessageSentToAllArray = $EmailHeaders->to; //Grab the “TO” header
$MessageSentToAllObject = $MessageSentToAllArray[0];
$MessageSentToMailbox = $MessageSentToAllObject->mailbox ."#". $MessageSentToAllObject->host; //Everything before and after the “#” of the recipient
$MessageSentFromAllArray = $EmailHeaders->from; //Grab the “FROM” header
$MessageSentFromAllObject = $MessageSentFromAllArray[0];
$MessageSentFromMailbox = $MessageSentFromAllObject->mailbox ."#". $MessageSentFromAllObject->host; //Everything before and after the “#” of the sender
$MessageSentFromName = $MessageSentFromAllObject->personal; //The name of the person who sent the email
$toArray = searchRecipient($MessageSentToMailbox); //Find the correct person to send the email to
if($toArray == FALSE) //If the alias they entered doesn’t exist…
{
$bounceback = 'Sorry the email in your message does not appear to be correct';
/* Send a bounceback email */
$mail = new PHPMailer(); // defaults to using php “mail()”
$mail -> ContentType = 'text/plain'; //Plain email
$mail -> IsHTML(false); //No HTML
$the_body = wordWrap($bounceback, 70); //Word wrap to 70 characters for formatting
$from_email_address = 'name#domain.com';
$mail->AddReplyTo($from_email_address, "domain.Com");
$mail->SetFrom($from_email_address, "domain.Com");
$address = $MessageSentFromMailbox; //Who we’re sending the email to
$mail->AddAddress($address, $MessageSentFromName);
$mail->Subject = 'Request'; //Subject of the email
$mail->Body = $the_body;
if(!$mail->Send()) //If the mail fails, send to customError
{
customError(1, $mail->ErrorInfo, "anon-email.php", "sending the email");
}
}
else //If the candidate address exists, forward on the email
{
$mail = new PHPMailer(); // defaults to using php “mail()”
$mail -> ContentType = 'text/plain'; //Plain E-mail
$mail -> IsHTML(FALSE); //No HTML
$the_body = wordwrap($Body, 70); //Wordwrap for proper email formatting
$from_email_address = "$MessageSentFromMailbox";
$mail->AddReplyTo($from_email_address);
$mail->SetFrom($from_email_address);
$address = $toArray[1]; //Who we’re sending the email to
$mail->AddAddress($address, $toArray[0]); //The name of the person we’re sending to
$mail->Subject = $EmailHeaders->subject; //Subject of the email
$mail->Body = ($the_body);
if(!$mail->Send()) //If mail fails, go to the custom error
{
customError(1, $mail->ErrorInfo, "anon-email.php", "sending the email");
}
}
/* Mark the email for deletion after processing */
imap_delete($connection, $MID);
}
imap_expunge($connection); // Expunge processes all of the emails marked to be deleted
imap_close($connection);
function searchRecipient() // function to search the database for the real email
{
global $MessageSentToMailbox; // bring in the alias email
$email_addr = mysql_query("SELECT email FROM tbl WHERE source='$MessageSentToMailbox'"); // temp store of the real email
$row = mysql_fetch_array($email_addr); //making temp store of data for use in program
if(empty($row['email']))
{
return FALSE;
}
else /* Else, return find the person's name and return both in an array */
{
$results = mysql_query("SELECT * FROM tbl WHERE email = '$email_addr'"); // temp store of both queries from this function
$row = mysql_fetch_array($results, $email_addr); //making temp store of data for use in program
$name = $row['author']; // taking the author data and naming its variable
return array($name, $email_addr); // this is the name and the real email address to be used in function call
}
}
function customError($errno, $errstr, $file, $line)
{
error_log("Error: [$errno] $errstr in $file at line number: $line",1, "name#domain.com","From: name#domain.com.com");
die();
}
Here is the first thing I would try:
It would appear that your function searchRecipient isn't being passed a parameter. Rather than use the global keyword, I would define it in your function call. Also, mysql_fetch_array does not pass back an associative array, which is what you are using in your next step. I would change that to mysql_fetch_assoc (it's the same thing essentially). There are also a few other minor syntax corrections in this function. Here are my proposed changes to that function. I think this should fix your problem. Or at least get you moving forward.
function searchRecipient($MessageSentToMailbox) // function to search the database for the real email
{
$email_addr = mysql_query("SELECT email FROM tbl WHERE source='$MessageSentToMailbox'"); // temp store of the real email
$row = mysql_fetch_assoc($email_addr); //making temp store of data for use in program
if(empty($row['email']))
{
return FALSE;
}
else /* Else, return find the person's name and return both in an array */
{
$email_addr = $row['email'];
$results = mysql_query("SELECT * FROM tbl WHERE email = '$email_addr'"); // temp store of both queries from this function
$row = mysql_fetch_assoc($results); //making temp store of data for use in program
$name = $row['author']; // taking the author data and naming its variable
return array($name, $email_addr); // this is the name and the real email address to be used in function call
}
}
You could also combine this into one query and make it a little easier. Here is that solution.
function searchRecipient($MessageSentToMailbox)
{
$results = mysql_query("SELECT email, author FROM tbl WHERE source='$MessageSentToMailbox'");
$row = mysql_fetch_assoc($results);
if(empty($row['email']) || empty($row['author'])) return false;
return array($row['email'], $row['author']);
}

Categories