I have a simple php file that sends an email using PHPMailer. It works great when run from the browser.
When I try to run it from a cron job I don't get the email. I have looked for quite a while for an answer here, but I have not been able to get it to work.
Most solution have to do with relative paths in the php code. I changed the paths on the require lines to be absolute if cron job has a different path.
I am pretty new to all of this, so any help would be appreciated.
I am probably missing something simple.
Thanks in advance for your help.
<?php
/* Namespace alias. */
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;
/* If you installed PHPMailer without Composer do this instead: */
require '/hermes/bosnaweb21a/b1837/ipw.whitmerd/public_html/test03/include/PHPMailer/PHPMailer.php';
require '/hermes/bosnaweb21a/b1837/ipw.whitmerd/public_html/test03/include/PHPMailer/Exception.php';
require '/hermes/bosnaweb21a/b1837/ipw.whitmerd/public_html/test03/include/PHPMailer/SMTP.php';
//SMTP needs accurate times, and the PHP time zone MUST be set
date_default_timezone_set('America/New_York');
echo phpinfo();
echo __DIR__;
// Email the results
$mailSubject = "Email Subject";
// Create the body of the mail
$mailBody = "Body of email";
/* Create a new PHPMailer object. Passing TRUE to the constructor enables exceptions. */
$mail = new PHPMailer(TRUE);
// Configure the mail object for iPower email account
$mail->IsSMTP();
$mail->SMTPDebug = 2;
$mail->SMTPAuth = true;
$mail->Host = "smtp.ipower.com";
$mail->Port = 25;
$mail->SMTPSecure = 'tls';
$mail->isHtml(true);
$mail->CharSet = 'UTF-8';
$mail->Encoding = 'base64';
$mail->Username = "validuser";
$mail->Password = "password";
$mail->setFrom('Example#gmail.com', 'Example Name');
$mail->Subject = $mailSubject;
$mail->addAddress('Example#gmail.com', 'Example Name');
$mail->Body = $mailBody;
$mailSendSuccess = $mail->send();
$mail = null;
// Success or failure message
if ($mailSendSuccess) {
echo "<br>Email was sent sucessfully.";
} else {
echo "<br>There was a problem sending the email.";
}
I wanted to get the phpinfo() information with the job running from cron job. So I was trying to create a file in a know location.
I tried this simple file operation that works well from the browser, but not from the cron job.
I commented out the code to grab the phpinfo into a file to just create a dummy file and that is not working.
<?php
$tempDir = '/hermes/bosnaweb21a/b1837/ipw.whitmerd/public_html/test03/misc/';
$tempFile = 'phpini_fromcron.html';
$fileContents = dirname(__DIR__);
$fileContents .= '<br>';
$fileContents .= 'Test file contents.';
// ob_start();
// phpinfo();
// $phpini = ob_get_contents();
// ob_end_clean();
// $fileContents .= $phpini;
$createFile = fopen($tempDir . $tempFile, 'w');
if (fwrite($createFile, $fileContents)) {
echo "File created.";
} else {
echo "There were problems.";
}
fclose($createFile);
Solved, kinda?
Turns out the directory name was the problem. I don't know what, as the permissions are set the same.
If anyone has a theory as to why, I would love to hear it.
Related
I am sending email with PHPMailer. My email design is available in the template.php file. I am pulling the contents of the template.php file with the file_get_contents method in my mail.php file. But I have such a problem, all my php codes in the template.php file are also visible. How can I hide them?
Mail.php
<?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
require_once 'assets/standart/db.php';
require 'assets/class/all.php';
$connect = new baglan();
$settings = new ayarlar();
// SMTP settings connect
$connect->connect('settings_smtp', '', '', 0);
$smtp_settings = $connect->connect->fetch(PDO::FETCH_ASSOC);
$smtp_mail = $smtp_settings['mail'];
// /SMTP settings connect
$template_file = 'PHPMailer/template.php';
if(file_exists($template_file)){
$mail_template = htmlspecialchars(file_get_contents($template_file));
}else{
die("Unable to locate the template file");
}
//Load Composer's autoloader
// require 'vendor/autoload.php';
//Create an instance; passing `true` enables exceptions
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = 0;
$mail->isSMTP();
$mail->Host = $smtp_settings['host'];
$mail->SMTPAuth = true;
$mail->Username = $smtp_settings['mail'];
$mail->Password = $smtp_settings['password'];
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
$mail->Port = $smtp_settings['port'];
//Recipients
$mail->setFrom("$smtp_mail", 'Mailer');
$mail->addAddress('example#gmail.com', 'Joe User'); //Add a recipient
// $mail->addAddress('ellen#example.com'); //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);
$mail->CharSet = 'UTF-8';
$mail->Subject = 'Here is the subject';
$mail->Body = $mail_template;
$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}";
}
Template.php
<?php
echo $forexample = 'Some words here';
?>
Don’t use file_get_contents for that, use include with output buffering. That way it will run the PHP code and you’ll see the results of its execution instead of the code itself.
You have to run the template file, not simply read it.
You can do that like this:
ob_start();
include ( $template_file );
$mail_template = ob_get_clean();
ob_start() (output-buffer start) causes all php script output (from echo etc) to go into an output buffer. output_get_clean() retrieves that output.
With
$mail_template = htmlspecialchars(file_get_contents($template_file));
you will just get the contents of the file into the variable $mail_template
You could use the eval() function as described here: https://www.php.net/manual/en/function.eval.php
But be very careful using it!
Caution: The eval() language construct is very dangerous because it allows
execution of arbitrary PHP code. Its use thus is discouraged. If you
have carefully verified that there is no other option than to use this
construct, pay special attention not to pass any user provided data
into it without properly validating it beforehand.
You could use it like this:
$mail_template_php = htmlspecialchars(file_get_contents($template_file));
$mail_template = eval($mail_template_php);
I'd like to use the latest PHPMailer library with require_once() instead of messing around with Composer. I'd like a pure xcopy deployment with minimal fuss.
Here's what I'm attempting to do:
require_once("src/PHPMailer.php");
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->Host = "smtp.gmail.com";
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = $smtpUsername;
$mail->Password = $smtpPassword;
$mail->setFrom($emailFrom, $emailFromName);
$mail->addAddress($emailTo, $emailToName);
$mail->Subject = 'PHPMailer GMail SMTP test';
$mail->msgHTML("test body");
$mail->AltBody = 'HTML messaging not supported';
if(!$mail->send()){
echo "Mailer Error: " . $mail->ErrorInfo;
}else{
echo "Message sent!";
}
I get the error message: Fatal error: Class PHPMailer not found in [....]\EmailTester.php on line 21
Line 21 is this: $mail = new PHPMailer;
This line is just a guess on my part: require_once("src/PHPMailer.php"); - clearly I need to include some file or files, but I can't tell which.
I'm working from the gmail example on github which is also not included in the zip download. But I can navigate to it in github. In that example file it begins like this:
use PHPMailer\PHPMailer\PHPMailer;
require '../vendor/autoload.php';
$mail = new PHPMailer;
I see no autoload.php file in the zip download, and after googling all over I see this implies using Composer. But there must be some way to simply do an include and get the files I need.
A few things puzzle me about this PHPMailer library and perhaps github in general:
When I download PHP Mailer from GitHub, why are so many listed files and folders not included in the downloaded zip file?
Why do they reference autoload.php which doesn't exist in the zip download?
Clearly I don't understand some things about github, but why not provide a working code sample instead of referencing dependencies that don't exist in the download, forcing people to find it elsewhere and hope they can figure out how to come back and plug it in correctly?
In this YouTube video titled Send Emails with PHP & Gmail, he downloads the same zip I downloaded and from the same place, yet his zip contains different files, including PHPMailerAutoload.php. Why am I getting completely different files than he gets? That video was published March 4, 2017 -- so, less than 1 year ago -- has it really changed so much since then?
In summary: How can I get PHPMailer working without external dependencies and installations such as Composer, and instead use require_once() to get what I need?
Here's the full working example (though you see a few variables that must be defined and set):
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'src/Exception.php';
require 'src/PHPMailer.php';
require 'src/SMTP.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 2; // 0 = off (for production use) - 1 = client messages - 2 = client and server messages
$mail->Host = "smtp.gmail.com"; // use $mail->Host = gethostbyname('smtp.gmail.com'); // if your network does not support SMTP over IPv6
$mail->Port = 587; // TLS only
$mail->SMTPSecure = 'tls'; // ssl is depracated
$mail->SMTPAuth = true;
$mail->Username = $smtpUsername;
$mail->Password = $smtpPassword;
$mail->setFrom($emailFrom, $emailFromName);
$mail->addAddress($emailTo, $emailToName);
$mail->Subject = 'PHPMailer GMail SMTP test';
$mail->msgHTML("test body"); //$mail->msgHTML(file_get_contents('contents.html'), __DIR__); //Read an HTML message body from an external file, convert referenced images to embedded,
$mail->AltBody = 'HTML messaging not supported';
// $mail->addAttachment('images/phpmailer_mini.png'); //Attach an image file
if(!$mail->send()){
echo "Mailer Error: " . $mail->ErrorInfo;
}else{
echo "Message sent!";
}
This worked for me, I also downloaded phpmailer from this address
https://sourceforge.net/projects/phpmailer/
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;
require '/source/PHPMailer2/src/Exception.php';
require '/source/PHPMailer2/src/PHPMailer.php';
require '/source/PHPMailer2/src/SMTP.php';
PHP Mailer original source :
PHP Mailer In gitHub
// for use PHP Mailer without composer :
// ex. Create a folder in root/PHPMAILER
// Put on this folder this 3 files find in "src"
// folder of the distribution :
// PHPMailer.php , SMTP.php , Exception.php
// include PHP Mailer
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
include dirname(__DIR__) .'/PHPMAILER/PHPMailer.php';
include dirname(__DIR__) .'/PHPMAILER/SMTP.php';
include dirname(__DIR__) .'/PHPMAILER/Exception.php';
// i made a function
/*
*
* Function send_mail_by_PHPMailer($to, $from, $subject, $message);
* send a mail by PHPMailer method
* #Param $to -> mail to send
* #Param $from -> sender of mail
* #Param $subject -> suject of mail
* #Param $message -> html content with datas
* #Return true if success / Json encoded error message if error
* !! need -> classes/Exception.php - classes/PHPMailer.php - classes/SMTP.php
*
*/
function send_mail_by_PHPMailer($to, $from, $subject, $message){
// SEND MAIL by PHP MAILER
$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';
$mail->isSMTP(); // Use SMTP protocol
$mail->Host = 'your_host.com'; // Specify SMTP server
$mail->SMTPAuth = true; // Auth. SMTP
$mail->Username = 'my_mail#your_host.com'; // Mail who send by PHPMailer
$mail->Password = 'your_passord_of_your_box'; // your pass mail box
$mail->SMTPSecure = 'ssl'; // Accept SSL
$mail->Port = 465; // port of your out server
$mail->setFrom($from); // Mail to send at
$mail->addAddress($to); // Add sender
$mail->addReplyTo($from); // Adress to reply
$mail->isHTML(true); // use HTML message
$mail->Subject = $subject;
$mail->Body = $message;
// SEND
if( !$mail->send() ){
// render error if it is
$tab = array('error' => 'Mailer Error: '.$mail->ErrorInfo );
echo json_encode($tab);
exit;
}
else{
// return true if message is send
return true;
}
}
/*
*
* END send_mail_by_PHPMailer($to, $from, $subject, $message)
* send a mail by PHPMailer method
*
*/
// use function :
send_mail_by_PHPMailer($to, $from, $subject, $message);
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';
I am working on a web application using PHP as a server-side and a jQuery framework as a client-side.
One of the scenarios of the application is to send an email with pdf file attached I am doing this using PHPMailer and Dompdf libraries.
I had created a function named sendMail in a file name send.php accept 4 params (receiver email,subject,data,email number) the last param is because I have 5 different emails may be sent depending on the situation and data param is the data will be rendered in the html email body.
The problem is when I call the function from send.php it work as expected the email sent and pdf file created and attached to the email .
but when I require send.php in any other file and call sendMail function I get the email only without any pdf file and the file not even generated or saved on the server.
send.php
<?php
require_once 'dompdf/autoload.inc.php';
// reference the Dompdf namespace
use Dompdf\Dompdf;
require 'PHPMailerAutoload.php';
$body = "test message";
sendMail('peter#w34.co','MLS mail',$body,5);
function sendMail($email,$subject,$body,$index){
$mail = new PHPMailer;
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // SMTP authentication
$mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for GMail
$mail->Host = "smtp.gmail.com"; // SMTP server
$mail->Port = 587; // SMTP Port
$mail->Username = "peterwilson.intake34#gmail.com"; // SMTP account username
$mail->Password = "Password"; // SMTP account password // TCP port to connect to
$mail->From = 'peter#example.com';
$mail->FromName = 'Wilson';
$mail->addAddress($email); // Add a recipient
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body=$body;
// instantiate and use the dompdf class
$dompdf = new Dompdf();
$dompdf->loadHtml($body);
// Render the HTML as PDF
$dompdf->render();
$output = $dompdf->output();
$file_to_save= "../work-orderes/file.pdf";
file_put_contents($file_to_save, $output);
$mail->addAttachment('../work-orderes/file.pdf');
if(!$mail->send()) {
// echo $mail->ErrorInfo;
} else {
return 1;
}
}
?>
save.php
<?php
require("sendSmtp/send.php");
session_start();
$body = "Hello World!";
sendMail('peter#w34.co','MLS mail',$body,5);
?>
Any suggestions about why Dompdf not works when calling it from any other file ??
What I have tried
removing dompdf and reinstall the latest stable version from
here
cleaning all code and just leave sendMail function and calling it
try to write the code from the beginnig
I solved it finally!
after debugging I found that everything going fine till $output = $dompdf->output(); after that I get an error on save the file using $file_to_save= "../work-orderes/file.pdf";
this work properly when I call the function sendMail() from send.php but when I call it from another file I get an error regarding accessing the path.
The Answer here that I should use the absolute path not the relative one like below
$file_to_save= $_SERVER['DOCUMENT_ROOT']."\work-orderes/file.pdf";
now the file saved successfully and attached to the email like expected!
I have a basic php emailer codes. I tried it on my personal site.It works very well.My site host is like ;
$mail->Host =mail.mysite.com
And i tried it another site, and of course i change the other values that needed,it doesnt work and i get this error : language string failed to load :connect host .
Also this site have a host like this : ***.secureserver.com . (not like mail.mysite.com)
I thought this error should about hosting and called the host company,they told me everything is ok about host,the code is wrong.
I try to find a solution,i hope somebody help
function mail_gonder($isim,$mesaj,$konu,$eposta)
{
require_once("class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = "*****.server.net";
$mail->SMTPAuth = true;
$mail->Username = "noreply#***.com";
$mail->Password = "****";
$mail->From = "noreply#****.com";
$mail->Fromname =$isim; //
$mail->AddAddress($eposta,$konu);
$mail->Subject =$konu;
$mail->Body = $mesaj;
if(!$mail->Send())
{
echo '<font color="#F62217"><b>Gönderim Hatası: ' . $mail->ErrorInfo . '</b></font>';
exit;
}
echo '<font color="#41A317"><b>Mesaj başarıyla gönderildi.</b></font>';
}
The fix for this is actually simple, set the language to this:
$mail = new PHPMailer();
$mail->SetLanguage("en", 'includes/phpMailer/language/');
Make sure the files you have are all local. Make sure you uploaded the files to your live webserver. Some servers are setup not to allow some type of connections to external resources. Uploading the files to your own server have been known to fix this.