How to connect PHP with SMTP

To connect PHP with SMTP, you can use a library like PHPMailer for secure and reliable email sending. SMTP allows PHP to send emails through external mail servers such as Gmail, Outlook, or Zoho. You need to configure the SMTP host, port, encryption method, and authentication credentials. PHPMailer handles all these configurations easily using the isSMTP() method. This ensures better deliverability and avoids common issues with PHP’s default mail() function.

How to Connect SMTP in PHP (Using PHPMailer)

1. Install PHPMailer

Option 1: Using Composer (recommended)

Put this comment in your project terminal:


composer require phpmailer/phpmailer

2. SMTP Email Sending Example


<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php'; // If using Composer

$mail = new PHPMailer(true);

try {
    // Server settings
    $mail->isSMTP();
    $mail->Host       = 'smtp.gmail.com';       // SMTP server
    $mail->SMTPAuth   = true;
    $mail->Username   = 'your_email@gmail.com'; // SMTP username
    $mail->Password   = 'your_app_password';    // SMTP password (use App Password)
    $mail->SMTPSecure = 'tls';                  // Encryption: 'ssl' or 'tls'
    $mail->Port       = 587;

    // Recipients
    $mail->setFrom('your_email@gmail.com', 'Your Name');
    $mail->addAddress('recipient@example.com', 'Recipient Name');

    // Content
    $mail->isHTML(true);
    $mail->Subject = 'Test Email via SMTP';
    $mail->Body    = 'This is a test email sent using SMTP with PHPMailer.';

    $mail->send();
    echo '✅ Message has been sent';
} catch (Exception $e) {
    echo "❌ Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
?>

Gmail Note:

 

SMTP Services You Can Use:

  • Gmail: smtp.gmail.com
  • Outlook: smtp.office365.com
  • Zoho: smtp.zoho.com
  • SendGrid, Mailgun, etc.