← Back to PHP Course | Chapter 16: Testing & Tools | Lesson 7 of 10

PHP Email Sending (PHPMailer)

Sending Mail with mail()

PHP's built-in mail() function can send basic email directly, letting you set headers for sender address, subject, and content type -- but it depends entirely on the server having a working mail transport configured.

Example: Sending Mail with mail()

php
<?php
$to = "[email protected]";
$subject = "Welcome";
$headers = "From: [email protected]";
$sent = mail($to, $subject, "Hello!", $headers);
echo $sent ? "Sent" : "mail() requires a configured mail transport";
?>

Introduction to PHPMailer

mail() offers no authentication or encryption and is frequently blocked or flagged as spam by modern mail providers; PHPMailer wraps proper SMTP support, attachments, and HTML formatting in a much more reliable package.

Example: Introduction to PHPMailer

php
<?php
// $mail = new PHPMailer\PHPMailer\PHPMailer();
// $mail->isSMTP();
echo "PHPMailer adds authentication, encryption, and reliable delivery over mail()";
?>

Configuring SMTP Settings

Configuring PHPMailer to relay through an authenticated SMTP server (like Gmail or a transactional provider such as Mailgun) is what actually gets email delivered reliably instead of landing in spam.

Example: Configuring SMTP Settings

php
<?php
// $mail->Host = 'smtp.gmail.com';
// $mail->SMTPAuth = true;
// $mail->Username = '[email protected]';
// $mail->Password = 'app-password';
echo "Relaying through authenticated SMTP avoids the spam folder";
?>

Adding Attachments

PHPMailer's addAttachment() method handles the encoding needed to send files alongside an email, but you should always confirm the file exists on disk before attempting to attach it.

Example: Adding Attachments

php
<?php
$file = "report.txt";
file_put_contents($file, "Report contents");
if (file_exists($file)) {
    echo "Attaching $file"; // $mail->addAttachment($file);
}
?>

HTML Email Sending

PHPMailer supports full HTML email bodies, letting you use custom styling and layout the same way you would in a web page, which plain mail() headers can't easily replicate.

Example: HTML Email Sending

php
<?php
// $mail->isHTML(true);
// $mail->Body = "<h1>Welcome</h1><p>Thanks for signing up!</p>";
echo "PHPMailer bodies can use full HTML, just like a web page";
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.