In PHP, SMTP (Simple Mail Transfer Protocol) is a common way to send emails. Compared to the built-in mail function, SMTP provides more reliable delivery and supports authentication. This tutorial shows you how to configure and send emails using the PHPMailer library.
PHPMailer is a popular and powerful email-sending library that supports SMTP, HTML emails, attachments, and more. You can install it via Composer:
# Install via Composer composer require phpmailer/phpmailer # Manual download wget https://github.com/PHPMailer/PHPMailer/archive/master.zip unzip master.zip
After installation, include the PHPMailer class file in your PHP script:
require 'PHPMailerAutoload.php';
Create a PHPMailer object and configure your SMTP server, port, encryption type, and login credentials:
$mail = new PHPMailer(); $mail->isSMTP(); $mail->Host = 'smtp.example.com'; $mail->SMTPAuth = true; $mail->Username = 'username'; $mail->Password = 'password'; $mail->SMTPSecure = 'tls'; // or 'ssl' $mail->Port = 587; // or 465
Configure the sender, recipient, subject, and body of the email:
$mail->setFrom('from@example.com', 'Sender Name'); $mail->addAddress('to@example.com', 'Recipient Name'); $mail->Subject = 'Email Subject'; $mail->Body = 'Email Body';
Call the send() method to send the email:
if ($mail->send()) { echo 'Email has been sent'; } else { echo 'Email could not be sent: ' . $mail->ErrorInfo; }
PHPMailer also supports advanced features such as:
By following these steps, you can easily implement SMTP email sending in your PHP project.