• 28 Jun, 2025

How to Automate Email Sending in PHP with Cron Jobs

How to Automate Email Sending in PHP with Cron Jobs

Learn how to automate email sending in PHP using cron jobs with this advanced guide. Includes PHPMailer setup, scheduling scripts, logging, security tips, and real-world automation examples.

Automation is a cornerstone of modern web development, and one common task developers often automate is email sending — for reports, notifications, or marketing campaigns. In this guide, we’ll walk you through how to automate email sending using PHP and cron jobs on a UNIX-based system.

By the end of this article, you'll have a reliable system in place that sends scheduled emails using PHP scripts triggered by cron jobs.


Prerequisites

  • A UNIX/Linux server (e.g., Ubuntu, CentOS)
  • PHP CLI installed (php -v)
  • Mail server configured (Sendmail, Postfix, or SMTP via PHPMailer)
  • Access to crontab (crontab -e)

Step 1: Create a PHP Script to Send Emails

Let’s begin by creating a PHP script that sends an email. We’ll use PHPMailer, a robust library that supports SMTP, HTML content, attachments, and more.

send_email.php

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php'; // Composer autoload

$mail = new PHPMailer(true);

try {
    // SMTP server settings
    $mail->isSMTP();
    $mail->Host       = 'smtp.example.com';
    $mail->SMTPAuth   = true;
    $mail->Username   = 'your_email@example.com';
    $mail->Password   = 'your_password';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = 587;

    // Recipients
    $mail->setFrom('your_email@example.com', 'Mailer');
    $mail->addAddress('recipient@example.com', 'Recipient Name');

    // Content
    $mail->isHTML(true);
    $mail->Subject = 'Automated Email';
    $mail->Body    = 'This is an automated email sent via a cron job.';

    $mail->send();
    echo "Email has been sent successfully\n";
} catch (Exception $e) {
    echo "Email could not be sent. Mailer Error: {$mail->ErrorInfo}\n";
}

Install PHPMailer using Composer:

composer require phpmailer/phpmailer

Step 2: Schedule the PHP Script Using Cron

Now that your PHP script is ready, schedule it using cron.

Step-by-step:

  1. Open the crontab editor:

    crontab -e
  2. Add a cron expression to execute the PHP script periodically.

Example (Send email every day at 8:00 AM):

0 8 * * * /usr/bin/php /path/to/send_email.php >> /var/log/email_cron.log 2>&1

Breakdown:

  • 0 8 * * *: Runs at 8:00 AM every day
  • /usr/bin/php: Path to PHP CLI
  • /path/to/send_email.php: Absolute path to your PHP script
  • >> /var/log/email_cron.log: Log output
  • 2>&1: Redirect stderr to stdout

Step 3: Testing and Logging

Test the Script Manually

php /path/to/send_email.php

View Logs

tail -f /var/log/email_cron.log

Security Best Practices

  • Environment variables: Avoid hardcoding credentials.
  • Error handling: Log all exceptions with try-catch blocks.
  • Permission control: Restrict read/execute access to the script.
  • Email rate limits: Monitor usage to avoid blacklisting.

Advanced Tips

$body = file_get_contents("https://example.com/daily-summary");
$mail->Body = $body;

2. Loop Through Multiple Recipients

$recipients = ['user1@example.com', 'user2@example.com'];
foreach ($recipients as $email) {
    $mail->clearAddresses();
    $mail->addAddress($email);
    $mail->send();
}

3. Database-Driven Scheduling

Store scheduling data in a DB and use one cron job to process all due emails.


Debugging Common Cron Issues

ProblemSolution
Script works manually but not via cronCheck PHP path, file permissions, and environment variables
Emails not sendingEnable PHPMailer debugging: $mail->SMTPDebug = 2;
No logs generatedVerify correct redirection in cron command

Use env inside your cron job to replicate environment:

* * * * * env > /tmp/env.output

Bonus: Using Laravel Scheduler (Optional)

$schedule->command('emails:send')->dailyAt('08:00');

Then run the scheduler via cron:

* * * * * php /path/to/artisan schedule:run >> /dev/null 2>&1

Conclusion

Automating email sending in PHP using cron jobs is powerful and scalable — ideal for periodic notifications, reports, and campaigns. With robust libraries like PHPMailer and the precision of cron jobs, you can automate almost any email workflow.

Whether you're building a startup MVP or running backend services, adding this kind of automation will save you time and reduce human error.

Have questions or need help? Drop them in the comments. 

Happy coding! 🚀

Y2A Post

Discover the innovative work in AI-generated blogs, seamlessly blending technology with creativity. This unique approach not only offers fresh perspectives on various topics but also ensures that content is engaging and relevant.