Skip to Content
Course content

128: Sending Mail with PHPMailer

Click on the "Edit" button in the top corner of the screen to edit your slide content.

If you've been poking around PHP tutorials, you've probably seen the mail() function. It looks inviting because it's built right into the language. You pass a recipient, a subject, and a message, and you're done, right? Wrong.

The myth that mail() is production-ready

The biggest misconception I see is that mail() is a reliable way to send emails to real people. Here is how that usually plays out: you write a simple contact form for a client, test it on your local machine (where it fails silently), push it to a server, and then realize that none of the emails are actually arriving. Or, worse, they all land in the "Spam" folder because the email was sent from a local server process without any proper authentication.

// This looks easy, but it's a nightmare in the real world
mail('client@example.com', 'New Lead', 'Someone filled out your form!'); 
// Result: Either a 'Warning: mail() failed' or a one-way ticket to the Spam folder.

The problem is that mail() relies on the server's local mail transport agent (like Sendmail or Postfix). Most modern mail servers (Gmail, Outlook, etc.) see an unauthenticated email coming from a random web server and immediately flag it as suspicious. You can't just "set a header" to fix this; you need a real handshake.

Why SMTP and PHPMailer are the professional choice

To get mail delivered, you need to use SMTP (Simple Mail Transfer Protocol). Instead of asking your web server to "hope for the best," you tell PHP to log into a real email account—like a SendGrid account, a Mailtrap test account, or a corporate SMTP server—and send the mail as a legitimate, authenticated user.

I use PHPMailer because it handles the heavy lifting. It manages the SMTP connection, handles attachments, and formats HTML emails properly. I've spent way too many hours of my life trying to manually construct MIME boundaries for attachments using raw strings; please, save yourself that misery and just use the library.

Wiring up your SMTP credentials

Assuming you've already run composer require phpmailer/phpmailer, the setup is straightforward. Let's imagine we're building a notification system for a boutique bakery that needs to alert the owner when a custom cake order comes in.

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);

try {
    // Server settings
    $mail->isSMTP();                                      // Send using SMTP
    $mail->Host       = 'smtp.mailtrap.io';               // Set the SMTP server to send through
    $mail->SMTPAuth   = true;                             // Enable SMTP authentication
    $mail->Username   = 'your_username_here';             // SMTP username
    $mail->Password   = 'your_password_here';             // SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;    // Enable TLS encryption
    $mail->Port       = 587;                              // TCP port to connect to

    // Recipients
    $mail->setFrom('orders@sweet-cakes.com', 'Cake Order System');
    $mail->addAddress('owner@sweet-cakes.com');           // Add a recipient

    // Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = 'New Custom Cake Order!';
    $mail->Body    = 'You have a new order for a Three-Tier Chocolate Fudge cake.';
    $mail->AltBody = 'You have a new order for a Three-Tier Chocolate Fudge cake.'; // Plain text for non-HTML clients

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

Handling attachments and dynamic data

One of the best things about PHPMailer is how it handles files. If your cake order system allows customers to upload a sketch of their design, you don't have to mess with binary encoding. You just call addAttachment().

I've found that adding a AltBody (the plain-text version) is a small detail that separates the pros from the amateurs. Some old-school email clients or security-hardened corporate filters strip HTML entirely. If you don't provide a plain-text alternative, your email might arrive as a blank page.




📋 Practical Task

Build a "Customer Support Ticket" Email Dispatcher

Your goal is to create a PHP script that simulates a support ticket system. You need to implement the following requirements using PHPMailer:

  • Input Simulation: Create an associative array representing a support ticket (include fields for customer_email, ticket_subject, issue_description, and a dummy path to a screenshot.jpg).
  • SMTP Configuration: Configure PHPMailer to use a testing service (like Mailtrap or a local MailHog instance).
  • Dynamic Content: The email body must be HTML and include the ticket details formatted in a clean HTML table.
  • File Attachment: Attach the screenshot.jpg file to the email.
  • Error Handling: Wrap the entire process in a try-catch block and output a user-friendly error message if the mail fails to send.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.