PHP
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Object-Oriented PHP
-
Section 5: Working with Data
-
Section 6: Modern PHP (PHP 8)
-
Section 7: Working with Files and Networking
-
Section 8: Common PHP Frameworks Overview
-
Section 9: Tooling and Ecosystem
-
Section 10: Practical Projects
-
Section 11: Interview Practice
-
Section 12: More Standard Library
-
Section 13: Data Structures and Algorithms in PHP
-
Section 14: More Practice Exercises
-
Section 15: More Security and Best Practices
-
Section 16: More Testing and Tooling
-
Section 17: WordPress-Style CMS Concepts
-
Section 18: Advanced OOP Practice
-
Section 19: More Web Fundamentals
-
Section 20: Database Practice
-
Section 21: PHP Manual: Array Functions
-
Section 22: PHP Manual: Date and Calendar Functions
-
Section 23: PHP Manual: Filesystem and Directory Functions
-
Section 24: PHP Manual: Filter and Var Handling
-
Section 25: PHP Manual: Math Functions
-
Section 26: PHP Manual: JSON and XML
-
Section 27: PHP Manual: Network and Stream Functions
-
Section 28: PHP Manual: Error and Exception Handling
-
Section 29: PHP Manual: Output Control and Misc
-
Section 30: PHP Manual: FTP, Zip, and Mail
-
Section 31: Modern PHP Frameworks Deep Dive
-
Section 32: PHP Design Patterns
-
Section 33: More Practice Exercises
-
Section 34: PHP Performance and Deployment
-
Section 35: More Interview Practice
-
Section 36: More PHP Standard Library
-
Section 37: PHP Concurrency and Async
-
Section 38: More Web Development Practice
-
Section 39: PHP Testing Deep Dive
-
Section 40: Composer and Package Development
-
Section 41: PHP Security Deep Dive
-
Section 42: More Practical Projects
-
Section 43: Legacy PHP Maintenance
-
Section 44: More Algorithm Practice
-
Section 45: Final Practice and Review
-
Section 46: PHP for E-Commerce Patterns
-
Section 47: PHP API Design Deep Dive
-
Section 48: PHP Caching Strategies
-
Section 49: PHP Queue and Background Jobs
-
Section 50: PHP Multi-Tenancy Patterns
-
Section 51: PHP Real-Time Features
-
Section 52: PHP CMS and Content Modeling
-
Section 53: PHP Internationalization
-
Section 54: More Framework-Specific Practice
-
Section 55: PHP Legacy Code Refactoring
-
Section 56: More Practice Projects Round 2
-
Section 57: PHP Command-Line Applications
-
Section 58: PHP and Microservices
-
Section 59: More Interview and Review Round 2
128: Sending Mail with PHPMailer
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 ascreenshot.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.jpgfile 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.
There are no comments for now.