PHPMailer not working in web page - php

I'm trying to send an email with PHPMailer, but it's not working for me so far.
On my FTP I've put 2 files, the class.phpmailer.php and sendEMail.php (this file is created by me), with this content:
<?php
require_once('/var/www/vhosts/MYWEBPAGE/httpdocs/class.phpmailer.php');
$mail = new PHPMailer();
$mail->isSMTP();
$mail->SMTPAuth = true;
$mail->Host = "mail.dom.com";
$mail->Username = "smpt#mail.com";
$mail->Password = "passwd";
$mail->Port = 25;
$mail->setFrom("my#mail.com", "me", 0);
$mail->addAddress("to#mail.com");
$mail->Subject = "test";
$body = "Hello World!";
$mail->Body = $body;
if(!$mail->send()) {
echo ("Invoice could not be send. Mailer Error: " . $mail->ErrorInfo);
} else {
echo "Invoice sent!";
}
?>
I'm missing something? When I execute this file, it shows me nothing, i mean before the if(!$mail->send()) {... It shows me every echo, but after that line, it shows me nothing.

It's because you've not read the readme that tells you what files you need, nor based your code on the examples provided. You've not loaded the SMTP class, nor the autoloader that will load it for you, so as soon as you try to send, it will fail to find the SMTP class. This will be logged in your web server logs like any other PHP fatal error.
Instead of this:
require_once('/var/www/vhosts/MYWEBPAGE/httpdocs/class.phpmailer.php');
do this:
require '/var/www/vhosts/MYWEBPAGE/httpdocs/PHPMailerAutoload.php';

Related

Getting "Mailer Error: Message body empty" when triggering with cronjob

I'm trying to send automatic emails every week with a cronjob.
However, I get the error message "Mailer Error: Message body empty".
For the email, I use a .html template.
When I trigger the .php script by calling its URL it works perfectly.
But when it's triggered by the cronjob it gives me that message.
The host I use is hostinger and I'm using their internal cronjob system.
This is my .php script.
use PHPMailer\PHPMailer\PHPMailer;
require 'vendor/autoload.php';
$msg = file_get_contents('./contact.html');
$msg = str_replace('$message', $message, $msg);
$mail = new PHPMailer;
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = 'myusername';
$mail->Password = 'mypassword';
$mail->setFrom('frommail#mail.com', 'frommail');
$mail->addReplyTo('mail#mail.com', 'mail');
$mail->addAddress($username I get from the database, $username I get from the database);
$mail->Subject = 'subject';
$mail->MsgHTML($msg);
if (!$mail->send()) {
echo 'Mailer Error: ' . $mail->ErrorInfo;
$response = ["Result" => "error"];
echo json_encode($response);
} else {
$response = ["Result" => "success"];
echo json_encode($response);
}
It's very likely that your cron job is run by a different user than when run via your web server, and that user may not have ownership or sufficient permissions to read the contact.html file. If msgHTML() fails, it will return an empty string, so you could check that before you try to send (though I notice you have omitted the send() call from the script in your question, and you don't show any error handling either).

PHPMailer $mail->send() showing results on page

I have PHPMailer working through Gmail. I've sent emails to myself to test that it's working, and it is. The user submits a signup form (very basic setup) on index.php, which then triggers sending the email.
My problem is that after submitting the form, it "echoes" to the page the process that it's going through: to give a sense of it, here's the start (3000 characters so I'm only including a bit):
2017-03-01 21:25:36 Connection: opening to smtp.gmail.com:587, timeout=300, options=array ( ) 2017-03-01 21:25:36 Connection: opened 2017-03-01 21:25:36 SERVER -> CLIENT: 220 smtp.gmail.com ...
This shows up directly on the page. I'm sure I could get around it by redirecting to another page on success, but it seems much easier to simply not print all of the information to the page in the first place. I've tested my code and it's definitely the $mail->send(); command that's triggering it.
Here's the code I'm using to call PHPMailer (it's inside <?php and ?> tags.
require_once "phpmailer/PHPMailerAutoload.php";
$mail = new PHPMailer;
$mail->SMTPDebug = 3;
$mail->isSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = true;
$mail->Username = "myemailaddress#gmail.com";
$mail->Password = "mypassword";
$mail->SMTPSecure = "tls";
$mail->Port = 587;
$mail->From = "myemailaddress#gmail.com";
$mail->FromName = "my name";
[![enter image description here][1]][1]
$mail->addAddress("towhoever#gmail.com", "their name");
$mail->isHTML(true);
$mail->Subject = "Testing email for phpmailer";
$mail->Body = "<i>Mail body in HTML</i>. It worked!";
$mail->AltBody = "This is the plain text version of the email content. Also, it worked!";
if($mail->send())
{
echo "Message has been sent successfully";
}
else
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
Misc. system information if it helps: I'm using XAMPP on Windows 10, running in localhost. I'm connected to my Gmail account.
Here's what the problem looks like on the page (I didn't screenshot much as I'm unsure how much is sensitive information):
PhpMailer have option to debug.
$mail->SMTPDebug // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
Comment $mail->SMTPDebug = 3; in the code.
$mail->SMTPDebug = 0; //after all functions work proper set to 0;

Error Sending Emails using PHPMailer over SMTP

I've had a look around as to why my PHP script was not sending any emails when I had the $mail->isSMTP(); set.
Before I go into the problem, I would like to point out that I am using mailgun.org as my SMTP server. My PHP script is simple, I have an HTML form that forwards data to a PHP file which in turn calls the PHPMailer script and sends an email.
Here is the code to my PHP Script:
date_default_timezone_set('Asia/Manila');
require 'phpmailer/PHPMailerAutoload.php';
// include 'phpmailer/class.phpmailer.php';
// require 'phpmailer/class.smtp.php';
$mail = new PHPMailer;
//$mail->isSMTP();
$mail->SMTPDebug = 0;
$mail->Debugoutput = 'html';
$mail->Host = "smtp.mailgun.org";
$mail->Port = 465;
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Username = ""; //Username removed
$mail->Password = ""; //Password removed
$mail->setFrom('', ''); //Email address and Name removed
$mail->addReplyTo($userMail, $firstName);
$mail->addAddress('emailOne#example.com', 'Name'); //Actual Values Changed
$mail->addAddress('emailTwo#example.com', 'Name'); //Actual Values Changed
$mail->addAddress('emailThree#example.com', 'Name'); //Actual Values Changed
$mail->Subject = 'New Application for website by '. $firstName;
$mail->msgHTML($theMessage);
$mail->AltBody = $theMessage;
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else { //Some HTML code here
}
Now then, as you can see, I have commented out the $mail->isSMTP(); line. This is because whenever I try to use it, the code does not load, and after a long wait gives a 500 error. (Sadly, by cPanel setup does not allow me to view apache logs).
I tried importing just the class.phpmailer.php file, but that gave me a fatal error that the class SMTP was not defined, which was expected. I then included the class.smtp.php file which gave me the same 500 error.
I had a look around StackOverflow and came across this answer however it did not help my case.
I have had a look at Mailgun's logs, but they have no record of the script even trying to connect.
Additional Information: If it matters, I have the following files in the same directory:
- sendMail.php //The script above
- class.phpmailer.php
- class.smtp.php
- PHPMailerAutoload.php
- index.html //Not important in this situation.
I hope someone will be able to help me out, I'm relying on the non-smtp method for now. :/
Try this working fine..!
date_default_timezone_set('Asia/Manila');
require 'phpmailer/PHPMailerAutoload.php';
// include 'phpmailer/class.phpmailer.php';
// require 'phpmailer/class.smtp.php';
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 1;
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;
$mail->Username = ""; //Username removed
$mail->Password = ""; //Password removed
$mail->addReplyTo($userMail, $firstName);
$mail->SetFrom('emailOne#example.com', 'my name');
$mail->Subject = 'New Application for website by '. $firstName;$mail->MsgHTML($theMessage);
$mail->AddAddress('aswad#yahoo.com', 'my name');
if($mail->Send()) {
echo "Message sent!";
}else {
echo "Mailer Error: " . $mail->ErrorInfo;
}

Error in sending SMTP mail

Try to send mail from window server using SMTP.
and i get this error
Fatal error: Class 'SMTP' not found in...
and when i use PHPmailerAutoload.php only then it gives
Fatal error: Call to undefined method SMTP::setDebugLevel() in...
My code is
error_reporting(E_ALL);
ini_set('display_errors','1');
require_once('class.phpmailer.php');
include("class.smtp.php");
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 1;
$mail->SMTPAuth = true;
$mail->Host = "mail.host.com.au";
$mail->Port = 25;
$mail->Username = "myusername";
$mail->Password = "mypassword";
$mail->SetFrom('info#company.com.au', 'First Last');
$mail->AddReplyTo("info#company.com.au","First Last");
$mail->Subject = "PHPMailer Test Subject";
$body = "test";
$mail->MsgHTML($body);
$address = "myemail#gmail.com";
$mail->AddAddress($address, "John Doe");
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
Please provide any suggestion.
i had the same problem doing this.. and i resolved it..
Open your PHPMailer and in that class.phpmailer.php and in that add this line at the starting in the php block: require_once('class.smtp.php');
It'll surely work.. or you can download that two files from this link:
https://github.com/abhishekpanjabi/e-Legal.git
Download phpmailer it has only two requird files and replace it with your phpmailer's files.. it'll work I've uploded image showing code.

Fatal error: Class 'PHPMailer' not found

I tried :include_once('C:\Inetpub\wwwroot\php\PHPMailer\PHPMailerAutoload.php');
Fatal error: Class 'PHPMailer' not found in C:\Inetpub\wwwroot\php\index.php on line 151
I place the PHPMailerAutoload.php in the same directory as my script.
Can someone help me with this ?
all answers are outdated now. Most current version (as of Feb 2018) does not have autoload anymore, and PHPMailer should be initialized as follows:
<?php
require("/home/site/libs/PHPMailer-master/src/PHPMailer.php");
require("/home/site/libs/PHPMailer-master/src/SMTP.php");
$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
$mail->Host = "smtp.gmail.com";
$mail->Port = 465; // or 587
$mail->IsHTML(true);
$mail->Username = "xxxxxx";
$mail->Password = "xxxx";
$mail->SetFrom("xxxxxx#xxxxx.com");
$mail->Subject = "Test";
$mail->Body = "hello";
$mail->AddAddress("xxxxxx#xxxxx.com");
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message has been sent";
}
?>
This answers in an extension to what avs099 has given above, for those who are still having problems:
1.Makesure that you have php_openssl.dll installed(else find it online and install it);
2.Go to your php.ini; find extension=php_openssl.dll enable it/uncomment
3.Go to github and downland the latetest version :6.0 at this time.
4.Extract the master copy into the path that works better for you(I recommend the same directory as the calling file)
Now copy this code into your foo-mailer.php and render it with your gmail stmp authentications.
require("/PHPMailer-master/src/PHPMailer.php");
require("/PHPMailer-master/src/SMTP.php");
require("/PHPMailer-master/src/Exception.php");
$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->IsSMTP();
$mail->CharSet="UTF-8";
$mail->Host = "smtp.gmail.com";
$mail->SMTPDebug = 1;
$mail->Port = 465 ; //465 or 587
$mail->SMTPSecure = 'ssl';
$mail->SMTPAuth = true;
$mail->IsHTML(true);
//Authentication
$mail->Username = "foo#gmail.com";
$mail->Password = "*******";
//Set Params
$mail->SetFrom("foo#gmail.com");
$mail->AddAddress("bar#gmail.com");
$mail->Subject = "Test";
$mail->Body = "hello";
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message has been sent";
}
Disclaimer:The original owner of the code above is avs099 with just my little input.
Take note of the additional:
a) (PHPMailer\PHPMailer) namespace:needed for name conflict resolution.
b) The (require("/PHPMailer-master/src/Exception.php");):It was missing in avs099's code thus the problem encountered by aProgger,you need that line to tell the mailer class where the Exception class is located.
Doesn't sound like all the files needed to use that class are present. I would start over:
Download the package from https://github.com/PHPMailer/PHPMailer by clicking on the "Download ZIP" button on the far lower right of the page.
extract the zip file
upload the language folder, class.phpmailer.php, class.pop3.php, class.smtp.php, and PHPMailerAutoload.php all into the same directory on your server, I like to create a directory on the server called phpmailer to place all of these into.
Include the class in your PHP project: require_once('phpmailer/PHPMailerAutoload.php');
As of 2021-07, and PHPMailer 6.5.0, without composer you need to do your includes in the following order:
$rdir = str_replace("\\", "/", __DIR__); //Root Dir
require $rdir.'/PHPMailer/src/Exception.php';
require $rdir.'/PHPMailer/src/PHPMailer.php';
require $rdir.'/PHPMailer/src/SMTP.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
You may need to tweak based on your directory structure.
The rest of the code works as expected.
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = SMTP::DEBUG_SERVER; //Enable verbose debug output
$mail->isSMTP(); //Send using SMTP
$mail->Host = 'smtp.yourserver.com'; //Set the SMTP server to send through
$mail->SMTPAuth = true; //Enable SMTP authentication
$mail->Username = 'no-reply#example.com'; //SMTP username
$mail->Password = 'password'; //SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; //Enable implicit TLS encryption
$mail->Port = 465; //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
//Recipients
$mail->setFrom('mail#example.com');
$mail->addAddress('mail#example.com', 'Joe User'); //Add a recipient
$mail->addAddress('mail#example.com', 'Joe Doe'); //Name is optional
$mail->addAddress('mail#example.com', 'Optional Name'); //Name is optional
$mail->addReplyTo('info#example.com', 'Information');
$mail->addCC('cc#example.com');
$mail->addBCC('bcc#example.com');
//Attachments
$mail->addAttachment('/var/tmp/file.tar.gz'); //Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); //Optional name
//Content
$mail->isHTML(true); //Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
This is just namespacing. Look at the examples for reference - you need to either use the namespaced class or reference it absolutely, for example:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
//Load composer's autoloader
require 'vendor/autoload.php';
I suggest you look into getting composer. https://getcomposer.org
Composer makes getting third-party libraries a LOT easier and using a single autoloader for all of them. It also standardizes on where all your dependencies are located, along with some automatization capabilities.
Download https://getcomposer.org/composer.phar to C:\Inetpub\wwwroot\php
Delete your C:\Inetpub\wwwroot\php\PHPMailer\ directory.
Use composer.phar to get the phpmailer package using the command line to execute
cd C:\Inetpub\wwwroot\php
php composer.phar require phpmailer/phpmailer
After it is finished it will create a C:\Inetpub\wwwroot\php\vendor directory along with all of the phpmailer files and generate an autoloader.
Next in your main project configuration file you need to include the autoload file.
require_once 'C:\Inetpub\wwwroot\php\vendor\autoload.php';
The vendor\autoload.php will include the information for you to use $mail = new \PHPMailer;
Additional information on the PHPMailer package can be found at https://packagist.org/packages/phpmailer/phpmailer
I was with the same problem except with a slight difference, the version of PHPMailer 6.0, by the good friend avs099 I know that the new version of PHPMailer since February 2018 does not support the autoload, and had a serious problem to instantiate the libraries with the namespace in MVC, I leave the code for those who need it.
//Controller
protected function getLibraryWNS($libreria) {
$rutaLibreria = ROOT . 'libs' . DS . $libreria . '.php';
if(is_readable($rutaLibreria)){
require_once $rutaLibreria;
echo $rutaLibreria . '<br/>';
}
else{
throw new Exception('Error de libreria');
}
}
//loginController
public function enviarEmail($email, $nombre, $asunto, $cuerpo){
//Import the PHPMailer class into the global namespace
$this->getLibraryWNS('PHPMailer');
$this->getLibraryWNS('SMTP');
//Create a new PHPMailer instance
$mail = new \PHPMailer\PHPMailer\PHPMailer();
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// $mail->SMTPDebug = 0; // 0 = off (for production use), 1 = client messages, 2 = client and server messages Godaddy POR CONFIRMAR
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
//Whether to use SMTP authentication
$mail->SMTPAuth = true; // authentication enabled
//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'ssl'; //Seguridad Correo Gmail
//Set the hostname of the mail server
$mail->Host = "smtp.gmail.com"; //Host Correo Gmail
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 465; //587;
//Verifica si el servidor acepta envios en HTML
$mail->IsHTML(true);
//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = 'tumail#gmail.com';
//Password to use for SMTP authentication
$mail->Password = 'tucontraseƱa';
//Set who the message is to be sent from
$mail->setFrom('tumail#gmail.com','Creador de PƔginas Web');
$mail->Subject = $asunto;
$mail->Body = $cuerpo;
//Set who the message is to be sent to
$mail->addAddress($email, $nombre);
//Send the message, check for errors
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
return false;
} else {
echo "Message has been sent";
return true;
}
Just from reading what you have written, you will need to add the file class.phpmailer.php to your directory as well.
PHPMailerAutoload needs to be in the same folder as class.phpmailer.php
This is the PHPMailerAutoload code that I assume this:
$filename = dirname(__FILE__).DIRECTORY_SEPARATOR.'class.'.strtolower($classname).'.php';
Just download composer and install phpMailler autoloader.php
https://github.com/PHPMailer/PHPMailer/blob/master/composer.json
once composer is loaded use below code:
require_once("phpMailer/class.phpmailer.php");
require_once("phpMailer/PHPMailerAutoload.php");
$mail = new PHPMailer(true);
$mail->SMTPDebug = true;
$mail->SMTPSecure = "tls";
$mail->SMTPAuth = true;
$mail->Username = 'youremail id';
$mail->Password = 'youremail password';
$mail_from = "youremail id";
$subject = "Your Subject";
$body = "email body";
$mail_to = "receiver_email";
$mail->IsSMTP();
try {
$mail->Host= "smtp.your.com";
$mail->Port = "Your SMTP Port No";// ssl port :465,
$mail->Debugoutput = 'html';
$mail->AddAddress($mail_to, "receiver_name");
$mail->SetFrom($mail_from,'AmpleChat Team');
$mail->Subject = $subject;
$mail->MsgHTML($body);
$mail->Send();
$emailreturn = 200;
} catch (phpmailerException $e) {
$emailreturn = $e->errorMessage();
} catch (Exception $e) {
$emailreturn = $e->getMessage();
}
echo $emailreturn;
Hope this will work.
I resolved error copying the files class.phpmailer.php , class.smtp.php to the folder where the file is PHPMailerAutoload.php, of course there should be the file that we will use to send the email.
I had a number of errors similar to this. Make sure your setFrom email address is valid in $mail->setFrom()

Categories