I’ve done some searching before this post and I still can’t seem to get this to work. I’m trying to setup a cron job with PHPMailer to send out an email every so often. The script below does work if I run it manually but does not work in the cron job scheduler.
For this example – I set it to run every minute. I’m thinking it has to do something with the “vendor/autoload.php” and it’s path not loading correctly? I didn’t add my SMTP credentials with api key for security reasons as well as recipients for this post.
Here is my cron job setup in Cpanel.
Here is my PHPMailer code:
// Import PHPMailer classes into the global namespace // These must be at the top of your script, not inside a function use PHPMailerPHPMailerPHPMailer; use PHPMailerPHPMailerSMTP; use PHPMailerPHPMailerException; // Load Composer's autoloader require 'vendor/autoload.php'; // Instantiation and passing `true` enables exceptions $mail = new PHPMailer(true); try { // Server settings // $mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output $mail->isSMTP(); // Send using SMTP $mail->Host = ''; // Set the SMTP server to send through $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = ''; // SMTP username $mail->Password = ''; // SMTP password $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted $mail->Port = 587; // TCP port to connect to // Recipients $mail->setFrom('email@email.com', ''); $mail->addAddress('email@email.com', ''); // Add a recipient $mail->addReplyTo('email@email.com', ''); // $mail->addCC('cc@example.com'); // $mail->addBCC(''); // Content $mail->isHTML(true); // Set email format to HTML $mail->Subject = 'PHPMailer email'; // $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->msgHTML(file_get_contents('email.html'), __DIR__); // Use this if not using the above code // ********* PHP-MAILER ********* // $mail->send(); echo 'Email sent!'; } catch (Exception $e) { echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}"; }
If anyone could help me, I would really appreciate it!
Advertisement
Answer
Can you share you error-message with us? I assume this will help a lot to find the issue.
I’ve shared my insights how to enable logging in a different post on stack overflow (see link below). This will explain how you can display errors in your cron execution:
https://stackoverflow.com/a/60250715/12880865
Please let me know if this helps you. If you’ll get a proper error message, please share it with us so we can dig further into your question.