I have an script in PHP and even saving and trying to execute it in different browsers It seems like it's cached or something because every change I do, it doesn't appear live.
EDIT 2
I'm trying this in my server and it works fine, if I change the file, the web changes as usual. My server is running a Debian with apache2 exactly as I have locally.
EDIT
I tried to remove the $app->post('/send-mail', 'AppmaticController:sendMail'); and it stills working!!
Class /app/controllers/AppmaticController.php
namespace Appmatic\Controllers;
use Appmatic\Errors\ErrorHandler;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
class AppmaticController
{
private $slimApp;
public function __construct($app)
{
$this->slimApp = $app;
}
public function sendMail(RequestInterface $request, ResponseInterface $response, $arguments)
{
$name = filter_var($request->getParsedBody()['name'], FILTER_SANITIZE_STRING);
$email = filter_var($request->getParsedBody()['email'], FILTER_SANITIZE_EMAIL);
$subject = filter_var($request->getParsedBody()['subject'], FILTER_SANITIZE_STRING);
$message = filter_var($request->getParsedBody()['message'], FILTER_SANITIZE_STRING);
$mail = new \PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.1and1.es';
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = 'info#nulltilus.com';
$mail->Password = 'pass';
$mail->SMTPSecure = 'tls';
$mail->setFrom($email, $name);
$mail->addAddress('info#nulltilus.com', 'Nulltilus');
$mail->isHTML(false);
$mail->Subject = $subject;
$mail->Body = $message;
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'El mensaje se ha enviado';
}
}
}
/public_html/index.php
<?php
use Appmatic\Controllers as Controllers;
use Appmatic\Database;
require '../vendor/autoload.php';
require '../app/controllers/AppmaticController.php';
require '../app/utils/ErrorHandler.php';
include '../app/config/constants.php';
$config = require '../app/config/config.php';
$app = new \Slim\App($config);
require '../app/routes.php';
$container = $app->getContainer();
$container['view'] = function () {
return new \Slim\Views\PhpRenderer('../app/views/');
};
$container['AppmaticController'] = function ($container) {
return new Controllers\AppmaticController($container);
};
$app->run();
/app/routes.php
<?php
$app->post('/send-mail', 'AppmaticController:sendMail');
Server: localhost, Apache2
OS: Ubuntu 16.04
PHP 7.0
Well, try restarting the web server :)
As you are not specifying which system you are on I'm going to explain 2 situations:
Windows
Go to the XAMPP screen and click "Stop" , once stapped hit "start" for the web server entry.
** Linux **
Based on your distro run either of these:
sudo service apache2 restart
sudo systemctl restart httpd.service
Also, I noticed a \ in your code that shouldn't be there, try removing that.
$mail = new \PHPMailer();
Should look like:
$mail = new PHPMailer();
PHPStorm, the IDE I use, turns mad. When I tried to close it, I realized I couldn't close it and when I tried to open the project, there's no changes made so that's the problem.
But when I opened the file before with Sublime changes were effective so I think that's a bug with PHPStorm or something similar.
Thanks everyone who tried to help :)
Related
i am trying to understand why my subject method in index.php triggers an error of not being defined.i am using phpmailer 5.2.7 with php 7.2 and wampserver 3.1.7
//here is my extended class from phpmailer//
<?php
include('phpmailer.php');
class Mail extends PhpMailer
{
// Set default variables for all new objects
public $From = 'xxxxxx#gmail.com';
public $FromName = MM;
public $Host = 'smtp.gmail.com';
public $Mailer = 'smtp';
public $SMTPAuth = true;
public $Username = 'xxxxxxx#gmail.com';
public $Password = 'xxxxxx';
public $SMTPSecure = 'ssl';
public $WordWrap = 75;
public function subject($subject)
{
$this->Subject = $subject;
}
public function body($body)
{
$this->Body = $body;
}
public function send()
{
$this->AltBody = strip_tags(stripslashes($this->Body))."\n\n";
$this->AltBody = str_replace(" ", "\n\n", $this->AltBody);
return parent::send();
}
}
and here is part of my index page where i have defined my variables
$to = $_POST['email'];
$subject = "Registration Confirmation";
$body = "<p>Thank you for registering at demo site.</p>
<p>To activate your account, please click on this link: <a href='".DIR."activate.php?x=$id&y=$activasion'>".DIR."activate.php?x=$id&y=$activasion</a></p>
<p>Regards Site Admin</p>";
$mail = new PHPMailer(true);
$mail->setFrom(SITEEMAIL);
$mail->addAddress($to);
$mail->subject($subject);
$mail->body($body);
$mail->send();
//redirect to index page
header('Location: index.php?action=joined');
exit;
Firstly, why are you using a version of PHPMailer that's literally years out of date? Get the latest, which has new features, fixed bugs, and fewer security holes. While you're upgrading, consider switching to using composer to manage your dependencies.
The problem you're having is quite straightforward: you have created a subclass that adds the subject() method, but the instance you've created in your script is of the original PHPMailer class, not your subclass. Do this instead:
$mail = new Mail(true);
Naming your class with a very generic "Mail" name is very likely to bring you an unexpected lesson on why namespacing is a good idea, so I'd recommend adding a namespace for your app to avoid name clashes.
While it's a good idea to subclass like this to set default values easily, it's also inviting you to check in credentials to your source repo, which is usually a bad idea. Better to use your child class to read those values from an environment file ("dot env") using a package like this.
This question already has answers here:
Fatal error: Class 'PHPMailer' not found
(12 answers)
Closed 3 years ago.
I'm getting the error : Class 'PHPMailer' not found in PHPMailer
I know the answer is probably out there but for my code, I can't seem to work it out.
I have a .php file where I created a class called Email, then a function inside this called sendEmail. Inside this function there is the PHPMailer files and code to send an email.
My code is :
function sendMail($con, $siteName, $siteLogo, $email1, $email2, $email3, $email4, $email5, $title, $message, $buttonText, $buttonLink) {
# Get the variables of the email using the variables inside the function's brackets upon request
error_reporting(E_ALL);
global $gmailEmail;
global $gmailPassword;
global $siteUrl;
require $siteUrl.'PHPMailer/PHPMailer.php';
require $siteUrl.'PHPMailer/SMTP.php';
require $siteUrl.'PHPMailer/Exception.php';
$mail = new PHPMailer;
$body = $this->emailTemplate($con, $siteName, $siteLogo, $email1, $email2, $email3, $email4, $email5, $title, $message, $buttonText, $buttonLink);
$mail->Host = "smtp.gmail.com";
$mail->SMTPDebug = 1;
$mail->SMTPAuth = true;
$mail->Host = "smtp.gmail.com";
$mail->Port = 587;
$mail->Username = $gmailEmail;
$mail->Password = $gmailPassword;
$mail->SetFrom("admin#".$siteName, $sitename." Admin");
$mail->AddReplyTo("admin#".$siteName, $sitename." Admin");
$mail->Subject = $title;
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!";
$mail->MsgHTML($body);
$emails = array($email1, $email2, $email3, $email4, $email5);
# Foreach email that is not empty, send the email
foreach((array)$emails as $email) {
$mail->AddAddress($email);
if (!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
}
}
But the error lies on the line of the code: $mail = new PHPMailer; , saying Class 'PHPMailer' not found
Someone said it's the use's :
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
But whenever I include these, I get this error: Class 'PHPMailer\PHPMailer\PHPMailer' not found
You don't have to have composer (though it's a good idea), but if you don't, you do have to load the classes yourself, and you have to import them into your namespace with use statements. All of this is covered in the readme and examples provided with PHPMailer, so it's not exactly kept secret.
The use statements must appear at the top of your script, before you try to use the classes, so perhaps the problem is that you're putting them within your function, which won't work – all that is standard PHP syntax, nothing unusual.
Alternatively you can use fully qualified class names, like this:
$mail = new PHPMailer\PHPMailer\PHPMailer;
Also I can see that you've based your code on a very old, obsolete example. That'a a bad idea - always use the latest.
Hi I am trying to use PHPMailer Library from GitHUB in my Codeigniter application.
I downloaded the code and unzipped in my application\library folder.
So there I have a folder called vendor inside which resides the source code for PHPMailer.
Now I created a File named Bizmailer_Controller.php.
<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
*
*/
class Bizmailer_Controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
require "vendor\phpmailer\phpmailer\PHPMailerAutoload";
$this->Bizmailer = new PHPMailer();
//Set the required config parameters
$this->Bizmailer->isSMTP(); // Set mailer to use SMTP
$this->Bizmailer->Host = 'smtp1.example.com;smtp2.example.com'; // Specify main and backup SMTP servers
$this->Bizmailer->SMTPAuth = true; // Enable SMTP authentication
$this->Bizmailer->Username = 'user#example.com'; // SMTP username
$this->Bizmailer->Password = 'secret'; // SMTP password
$this->Bizmailer->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$this->Bizmailer->Port = 465;
//return $api;
}
}
Now in my controllers I am trying to load it like this :
$this->load->library('Bizmailer');
$mail = new Bizmailer();
And I Get this error :
An Error Was Encountered
Unable to load the requested class: Bizmailer
So Please guide me how I can load or integrate this library in Codeigniter.
here is a guide
1. installing PHP Mailer
Download the latest PHPMailer Build from Github.
You can find the project here
Click now on "clone or download" and download it as zip - as in the image below is shown.
The folder in the zip is called PHPMailer-master.
Unzip this in your application/third_party/ folder and rename the folder to phpmailer. You should see something like this
2. PHP Mailer Library
Imho its best to create a library which handles your PHPMailer Object (Phpmailer_library.php)
This library could look like
class Phpmailer_library
{
public function __construct()
{
log_message('Debug', 'PHPMailer class is loaded.');
}
public function load()
{
require_once(APPPATH."third_party/phpmailer/PHPMailerAutoload.php");
$objMail = new PHPMailer;
return $objMail;
}
}
3. Using this library in one of your controllers, models etc.
class Welcome extends CI_Controller {
public function index()
{
$this->load->library("phpmailer_library");
$objMail = $this->phpmailer_library->load();
}
}
i think this should pretty much do the job.
If you've any troubles, don't hesitate to ask ;)
Update 25.06.2018
Since the PHPMailer guys removed the autoloader you've two options now:
1.) via Composer
for those who didn't know - Codeigniter supports Composer - you simply have to activate the autoload - you can find this in your config.php
$config['composer_autoload'] = true;
For more informations take a look here
After that - run composer like
composer require phpmailer/phpmailer
You now should have within your application/vendor folder the phpmailer files.
The library should look like
class Phpmailer_library
{
public function __construct()
{
log_message('Debug', 'PHPMailer class is loaded.');
}
public function load()
{
$objMail = new PHPMailer\PHPMailer\PHPMailer();
return $objMail;
}
}
2.) download
follow step 1
The library should look like
class Phpmailer_library
{
public function __construct()
{
log_message('Debug', 'PHPMailer class is loaded.');
}
public function load()
{
require_once(APPPATH.'third_party/phpmailer/src/PHPMailer.php');
require_once(APPPATH.'third_party/phpmailer/src/SMTP.php');
$objMail = new PHPMailer\PHPMailer\PHPMailer();
return $objMail;
}
}
and everything else should remain the same
**
UPDATE AUGUST 2019
**
At first, download the latest PHPMailer library files and place all the files in the application/third_party/ folder of your CodeIgniter application.
Now, create a library (application/libraries/Phpmailer_lib.php) to handle the PHPMailer object.
Include the PHPMailer library files.
Initialize the PHPMailer class.
Return the PHPMailer object.
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
class PHPMailer_Lib
{
public function __construct(){
log_message('Debug', 'PHPMailer class is loaded.');
}
public function load(){
// Include PHPMailer library files
require_once APPPATH.'third_party/phpmailer/Exception.php';
require_once APPPATH.'third_party/phpmailer/PHPMailer.php';
require_once APPPATH.'third_party/phpmailer/SMTP.php';
$mail = new PHPMailer(true);
return $mail;
}
}
Now send email via SMTP server using PHPMailer from your controller using this code.
class Email extends CI_Controller{
function __construct(){
parent::__construct();
}
function send(){
// Load PHPMailer library
$this->load->library('phpmailer_lib');
// PHPMailer object
$mail = $this->phpmailer_lib->load();
// SMTP configuration
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'user#example.com';
$mail->Password = '********';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->setFrom('info#example.com', 'CodexWorld');
$mail->addReplyTo('info#example.com', 'CodexWorld');
// Add a recipient
$mail->addAddress('john.doe#gmail.com');
// Add cc or bcc
$mail->addCC('cc#example.com');
$mail->addBCC('bcc#example.com');
// Email subject
$mail->Subject = 'Send Email via SMTP using PHPMailer in CodeIgniter';
// Set email format to HTML
$mail->isHTML(true);
// Email body content
$mailContent = "<h1>Send HTML Email using SMTP in CodeIgniter</h1>
<p>This is a test email sending using SMTP mail server with PHPMailer.</p>";
$mail->Body = $mailContent;
// Send email
if(!$mail->send()){
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
}else{
echo 'Message has been sent';
}
}
}
There is php mailer library for Codeigniter 2/3, you can check this and this.
I've written a function within Controller to use PHPMailer and it works fine. After that I need this Function frequently and eventually I decide to write Library. But when do this and load Library within Controller, It has error like this :
Message: Call to undefined method PHPMailerOAuth::isSMTP()
After all I've figured out there is problem with path! I've tried what ever you're thinking but it doesn't work!
I've tried Controller as library
I've tried include(),require_once(),require, with or without APPATH.
I've search as much as I could. Even I've read about Third Party but I don't understand.
Is there any idea to load PHPMailer file within Library?
Thank you in advance.
It's library called PHPMailer.php
class PHPMailer {
public function singleMail($setFromTitle,$setToMail,$setToName,$setSubject,$setMessage)
{
date_default_timezone_set('Etc/UTC');
require 'vendor/phpmailer/phpmailer/PHPMailerAutoload.php';
require 'vendor/autoload.php';
$mail = new PHPMailerOAuth;
$mail->CharSet = 'UTF-8';
$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->Debugoutput = 'html';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->AuthType = 'XOAUTH2';
$mail->oauthUserEmail = "XXX#gmail.com";
$mail->oauthClientId = "XXX";
$mail->oauthClientSecret = "XXX";
$mail->oauthRefreshToken = "XXX";
$mail->setFrom('XXXy#zounkan.com', $setFromTitle);
$mail->addAddress($setToMail, $setToName);
$mail->Subject = $setSubject;
$mail->msgHTML($setMessage);
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
}
And it's how I load this library within Controller's function :
$this->load->library('PHPMailer');
$this->phpmailer->singleMail($setFromTitle,$setToMail,$setToName,$setSubject,$setMessage);
According to PHPMailer's owner, he helped me and eventually solve this problem!
It should happen for every programmer and when I fixed it I surprised! The problem was about the class name! I define PHPMailer class as Library's class and it's not allowed! So intead of code above (That I'v mentioned) I should try this and it works fine as well :
class Sendingmail {
public function singleMail($setFromTitle,$setToMail,$setToName,$setSubject,$setMessage) {
// Rest of codes
}
}
So don't named your class to PHPMailer or something like this which probably has defined in core functions!
I was following PHPMailer tutorial and some tutorials in Internet but I still can't make execution less than 2 second. On many website it says it shouldn't take more than 0.4s. I tried it from my local machine and from AWS machine. Execution time same.
class BatchMailer {
private static $mail;
private static $initialized = false;
private static function initialize() {
if (self::$initialized)
return;
self::$mail = new PHPMailer;
self::$mail->SMTPDebug = 2;
self::$mail->isSMTP();
self::$mail->Host = 'smtp.gmail.com';
self::$mail->Port = 587;
self::$mail->SMTPSecure = 'tls';
self::$mail->SMTPAuth = true;
self::$mail->Username = '***';
self::$mail->Password = '***';
self::$mail->SMTPKeepAlive = true;
self::$mail->setFrom('***#gmail.com', 'Title');
self::$mail->isHTML(true);
self::$mail->AltBody = 'Please use an HTML-enabled email client to view this message.';
self::$initialized = true;
}
public static function setSubject($subject) {
self::initialize();
self::$mail->Subject = $subject;
}
public static function setBody($body) {
self::initialize();
self::$mail->Body = stripslashes($body);
}
public static function sendTo() {
self::initialize();
self::$mail->clearAddresses();
$recipients = array(
'***#gmail.com' => 'Person One'
);
foreach($recipients as $email => $name) {
self::$mail->AddCC($email, $name);
}
self::$mail->send();
return;
}
static function test() {
self::setSubject('subject');
self::setBody('body');
self::sendTo();
}
}
SMTP is often slow, especially when things like greetdelay/tarpitting are used as anti-spam measures. 2 seconds is not that slow - the SMTP spec allows for timeouts of 10-20 minutes! It's really unsuited to real-time use, i.e. during a web page submission, but that doesn't seem to stop many trying to use it that way. To maximise performance you can install a local mail server to use as a relay, or hand off your message send to a separate process that doesn't mind waiting for a while, for example by submitting using an async ajax request from your page so the user is not blocked from doing other things.
If you're sending larger volumes of email it's important to use a relay and SMTP keepalive while submitting it. I have no trouble sustaining over 200 messages/second with PHPMailer.
Nice class BTW - tidier than most of the things I see on SO! $initialized is not needed - just check whether self::$mail is set instead.