Current Location: Home> Latest Articles> PHP SMTP Configuration and Email Sending Tutorial with PHPMailer

PHP SMTP Configuration and Email Sending Tutorial with PHPMailer

M66 2025-08-08

Steps to Send Email via SMTP in PHP

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.

Install PHPMailer

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

Load PHPMailer Class

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

require 'PHPMailerAutoload.php';

Configure SMTP Settings

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

Set Email Content

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';

Send the Email

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;
}

Additional Features

PHPMailer also supports advanced features such as:

  • Send HTML-formatted emails: $mail->isHTML(true);
  • Add attachments: $mail->addAttachment('file.txt');
  • Set reply-to address: $mail->addReplyTo('reply@example.com');

By following these steps, you can easily implement SMTP email sending in your PHP project.