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).
Related
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';
Email sends correctly, but then everything on my submission page disappears (although in the url it says it is the same page) except the echo statement saying 'Message sent successfully'.
I want to have a 'congratulations' page or something less cheesy to greet the user after they are sent the validation email...
I've tried searching the class.phpmailer.php for a redirect function but theres nothing. I'm sure its something simple but I cant seem to locate whats causing this.
<?php
require ('/config.inc.php');
require '../PHPMailer/PHPMailerAutoload.php';
if(mysqli_affected_rows($dbc) == 1){
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPSecure = 'ssl';
$mail->Host = "smtp.gmail.com"; // SMTP server
$mail->Port = 465;
$mail->SMTPAuth = true;
$mail->Username = "censored#gmail.com";
$mail->Password = "censored";
//Set who the message is to be sent from
$mail->setFrom('censored#gmail.com');
//Set an alternative reply-to address
$mail->addReplyTo('censored#gmail.com');
//Set who the message is to be sent to
$mail->addAddress($trimmed['email']);
//Set the subject line
$mail->Subject = 'PHPMailer mail() test';
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->msgHTML('Thank you for registering at The Circle Of Pi. To activate your account,
please click on this link:\n\n' . BASE_URL . 'activate.php?x=' . urlencode($e) . "&y=$a");
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
//Attach an image file
//$mail->addAttachment('images/phpmailer_mini.png');
//send the message, check for errors
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!1";
}
exit();
}else {
echo '<p class=\"error\">You could not be registered due to a system error. We apologize
for any inconvenience.</p>';
}
}else{
echo '<p class = \"error\">That email address has already been registered. If you have
forgotten your password, use the link at the right to have your password sent to you</p>';
}
} else {
echo '<p class = \"error\">Please try again.</p>';
}
mysqli_close($dbc);
}
?>
If your request is POST then you're calling exit() after 'Message sent!1' echo.
else {
echo "Message sent!1";
}
exit();
On your:
<form method="post">
Add a action to it such as:
<form method="post" action="{pickaname}.php">
and create a file called {pickaname}.php and make it when all the data is inserted it will redirect the user to your congratulations page.
I have been trying to make the contact form on my website to work and I've spent weeks trying to figure it out and I couldn't.
Here's the problem - I purchased a web template and it came with the PHPMailer. I'm now done plugging my content into the template, but the contact form has been a pain. I've followed the instructions the best I know on the PHP file, but it's giving me an "Internal Server Error" when I am testing the contact form.
Here's the code that came with my purchase:
$name = trim($_POST['name']);
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$site_owners_email = 'name#mydomain.com'; // Replace this with your own email address
$site_owners_name = 'My Name'; // Replace with your name
try {
require_once('/Beta-BRC/php/PHPMailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';
$mail->From = $email;
$mail->FromName = $name;
$mail->Subject = "[WEB Form] ".$subject;
$mail->AddAddress($site_owners_email, $site_owners_name);
$mail->Body = $message;
$mail->Mailer = "smtp";
$mail->Host = "smtp.gmail.com"; // Replace with your SMTP server address
$mail->Port = 465;
$mail->SMTPSecure = "SSL";
$mail->SMTPAuth = true; // Turn on SMTP authentication
$mail->Username = "name#mydomain.com"; // SMTP username
$mail->Password = "mypassword"; // SMTP password
//echo "true";
if($mail->Send()) {
echo "true";
} else {
echo "Error sending: " . $mail->ErrorInfo;
}
} catch (Exception $e) {
echo $e;
}
Quick note - I've alrealy tried using a GMAIL account on this part but it still does not work.
$mail->Username = "name#mydomain.com"; // SMTP username
$mail->Password = "mypassword"; // SMTP password
There's no need to log into Gmail with phpmailer. Below is an example of my phpmailer function using the default settings.
public function sendEmail($toaddress,$toname,$subject,$message){
if($template = file_get_contents('/home/username/domains/mydomain.com/public_html/html/email-template.html')){
$template = str_replace("[SUBJECT]",$subject,$template);
$template = str_replace("[CONTENT]",nl2br($message),$template);
$mailer = new PHPMailer;
$mailer->XMailer = "Organization Name 4.0.0";
if($this->is_logged_in()){
$mailer->AddCustomHeader("X-Originating-User-ID",$this->acct['id']);
}
$mailer->AddCustomHeader("X-Originating-IP",$_SERVER['REMOTE_ADDR']);
$mailer->setFrom("outbound#mydomain.com","From Name");
$mailer->AddAddress($toaddress,$toname);
$mailer->Subject = $subject;
$mailer->MsgHTML($template);
$mailer->AltBody = $message;
return $mailer->Send();
}else{
return false;
}
}
The email address listed doesn't actually exist. The email is just being sent from my server and phpmailer just says it's from that email address.
Try modifying my function to suit your needs and let me know how that works.
Note: You'll need to make sure your mail server is turned on for this to work
Although you don't have to use my function at all. Try debugging your code by checking some error logs on your server. Typically in the apache error logs (if you're running apache, however). Checking error logs is a huge part of troubleshooting your code and often can help you become more proactive.
I hope this helps even the slightest!
The specific cause of the Internal Server Error is the incorrect path you've supplied to the require_once statement that loads the PHPMailer class.
The path you've supplied is /Beta-BRC/php/PHPMailer/class.phpmailer.php, where the correct statement should be
require_once('/home/trsta/public_html/Beta-BRC/php/PHPMailer/class.phpmailer.php');
or perhaps more generally:
require_once($_SERVER['DOCUMENT_ROOT'].'/home/trsta/public_html/Beta-BRC/php/PHPMailer/class.phpmailer.php');
You've provided effectively a URL, but PHP requires the path in the server file system, which is not the same.
That should get you past this error. It's possible that there are others.
I have a php page containing PHPMailer. Apperently it was working in both the test server and the production server. It was in a separate php file, but since I need to do send different kinds of email with different alert messages on screen, I placed my code on the same php file as my form.
What I did is:
if(isset($_POST))
{
require_once('PHPMailer/class.phpmailer.php');
$mail = new PHPMailer(true);
if(isset($_POST['feedback_mail']))
{
$mail->Host = "my mail host"; // SMTP server
$mail->SMTPDebug = 0;
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Username = "the account that I will be using"; // SMTP account username
$mail->Password = "my password";
$mail->AddReplyTo($_POST['Email'], $_POST['Name']);
$mail->AddAddress('address to where I will send it', 'Name');
$mail->SetFrom($_POST['Email'], $_POST['Name']);
$mail->Subject = 'Subject'.$_POST['Subject'];
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
$mail->MsgHTML($_POST['Body']);
$mail->Send();
$marker = 1;
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
$marker = 0;
} else {
$marker = 1;
}
}
}
When I try to send an email message, it says that the message is sent, but I have been waiting for almost an hour but there is still no message recieved on my email. I know that my test server allows sending of email because I also have another application that can send mails. And I am using the same account for sending these mails. How do I know if PHPMailer is really working or not?
EDIT: I found out it might probably be my local network connection that's stopping the mail. I just tried running the from on a VPN connection and somehow it recieved an email.
Either my network connection is having problems or the server is deliberately blocking IP's from my country.
I came across a bizarre issue with PHPmailer (version 5.1) that I'm trying to workaround. I've seen quite a bit of good feedback on here, so I thought I would give it a try. I've found that when I attempt to create a customized confirmation message with a conditional statement based on $mail->send(), I receive duplicate emails. I can duplicate it with the generic testemail.php script that comes with the PHPMailer download. Here's the code:
require '../class.phpmailer.php';
try {
$mail = new PHPMailer(true); //New instance, with exceptions enabled
$mail->SMTPDebug = 1;
$mail->IsSMTP(); // tell the class to use SMTP
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Port = 25; // set the SMTP server port
$mail->Host = "mail.domain.com"; // SMTP server
$mail->Username = "username"; // SMTP server username
$mail->Password = "password"; // SMTP server password
$mail->IsSendmail();
$mail->From = "example_from#domain.com";
$mail->FromName = "First Last";
$to = "example#domain.com";
$mail->AddAddress($to);
$mail->Subject = "PHP Mailer test";
$message = "This is a test. \n";
$mail->Body = $message;
$mail->Send();
if ($mail->Send()) {
echo 'Message has been sent.';
} else {
echo "Mailer Error: " . $mail->ErrorInfo;
}
} catch (phpmailerException $e) {
echo $e->errorMessage();
}
The above code echoes the "Message has been sent" confirmation, but then sends two emails. If I comment out the $mail->send() line, I still receive the "message has been sent" confirmation and only get one message. If I remove the conditional statement and leave the $mail->send() line commented out, no email is sent.
Why does adding a conditional statement cause an email to be sent without calling the $mail->send() method?What is the proper way of adding a customized confirmation message?
When you put $mail->Send() in your conditional, you're actually calling it again, sending another message, and checking if that second message was sent.
If you just keep
if ($mail->Send()) {
echo 'Message has been sent.';
} else {
echo "Mailer Error: " . $mail->ErrorInfo;
}
and get rid of the original, unconditional Send call, you should be fine.
Alternatively, if it's clearer for you or if you need to do some processing elsewhere that depends on whether the message was successfully sent, you could do the essentially equivalent:
$status = $mail->Send();
if ($status) {
echo 'Message has been sent.';
} else {
echo "Mailer Error: " . $mail->ErrorInfo;
}