Current Location: Home> Latest Articles> Detailed Guide to Sending Emails via SMTP in PHP Using PHPMailer

Detailed Guide to Sending Emails via SMTP in PHP Using PHPMailer

gitbox 2025-08-08

What is SMTP Email Sending

SMTP (Simple Mail Transfer Protocol) is the standard protocol for email transmission over the internet. Using SMTP, PHP developers can send emails that include text, attachments, and even images.

Installing PHPMailer Library

PHPMailer is a widely-used PHP library for sending emails, supporting SMTP and various email formats. You can install PHPMailer using Composer with the following command:

<span class="fun">composer require phpmailer/phpmailer</span>

Including the PHPMailer Class

After installation, include the autoload file in your PHP script to use the PHPMailer class:

<span class="fun">require 'vendor/autoload.php';</span>

Configuring SMTP Parameters

Create a PHPMailer instance and set SMTP server details, including server address, authentication, and encryption method:

$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'your-password';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;

Please replace the SMTP server address, username, and password above with your actual information.

Setting Email Content

Specify the sender, recipient, subject, and body of the email:

$mail->setFrom('[email protected]', 'Your Name');
$mail->addAddress('[email protected]', 'Recipient Name');
$mail->Subject = 'Test Email';
$mail->Body = 'This is a test email.';

Sending the Email

Call the send() method to send the email and handle the result with a message:

if ($mail->send()) {
    echo 'Email sent successfully.';
} else {
    echo 'Email sending failed. Error: ' . $mail->ErrorInfo;
}

Complete Example Code

require 'vendor/autoload.php';
$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'your-password';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->setFrom('[email protected]', 'Your Name');
$mail->addAddress('[email protected]', 'Recipient Name');
$mail->Subject = 'Test Email';
$mail->Body = 'This is a test email.';
if ($mail->send()) {
    echo 'Email sent successfully.';
} else {
    echo 'Email sending failed. Error: ' . $mail->ErrorInfo;
}

Conclusion

This article demonstrated how to send emails via SMTP in PHP using the PHPMailer library. It included all steps from installing the library, including classes, configuring SMTP settings, to setting email content and sending emails. With these skills, you can easily integrate email functionality into your PHP projects.