PHP Email Sending (PHPMailer)
In this page:
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
$to = "[email protected]";
$subject = "Welcome";
$headers = "From: [email protected]";
$sent = mail($to, $subject, "Hello!", $headers);
echo $sent ? "Sent" : "mail() requires a configured mail transport";
?>
Login to try C/C++/Java/PHP code in the editor
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
// $mail = new PHPMailer\PHPMailer\PHPMailer();
// $mail->isSMTP();
echo "PHPMailer adds authentication, encryption, and reliable delivery over mail()";
?>
Login to try C/C++/Java/PHP code in the editor
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
// $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";
?>
Login to try C/C++/Java/PHP code in the editor
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
$file = "report.txt";
file_put_contents($file, "Report contents");
if (file_exists($file)) {
echo "Attaching $file"; // $mail->addAttachment($file);
}
?>
Login to try C/C++/Java/PHP code in the editor
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
// $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 try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: