How to mail using google smtp in php

To send emails using Google SMTP in PHP, you'll need to configure your PHP script to use Google's SMTP server. Here's a step-by-step guide:

Prerequisites:

  1. You have a Google account and have enabled the "Less secure app access" option in your account settings. This is required for PHP scripts to access your Google account.
  2. You have a PHP script that can send emails using SMTP.

Step 1: Configure your PHP script

In your PHP script, you'll need to set the following variables:

Here's an example of how you can set these variables:

<?php
define('SMTP_HOST', 'smtp.gmail.com');
define('SMTP_PORT', 587);
define('SMTP_USERNAME', '[email protected]');
define('SMTP_PASSWORD', 'your_password');
define('FROM_EMAIL', '[email protected]');
?>

Step 2: Use the PHPMailer library (optional)

To simplify the process of sending emails using Google SMTP, you can use the PHPMailer library. You can download the library from the official website or install it using Composer.

Here's an example of how you can use PHPMailer to send an email:

<?php
require_once 'PHPMailer/PHPMailer.php';
require_once 'PHPMailer/SMTP.php';

$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->isSMTP();
$mail->Host = SMTP_HOST;
$mail->Port = SMTP_PORT;
$mail->SMTPAuth = true;
$mail->Username = SMTP_USERNAME;
$mail->Password = SMTP_PASSWORD;
$mail->setFrom(FROM_EMAIL, 'Your Name');
$mail->addAddress('[email protected]', 'Recipient Name');
$mail->Subject = 'Test Email';
$mail->Body = 'This is a test email sent using Google SMTP';

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

Step 3: Send the email

Once you've configured your PHP script and set up the email details, you can send the email using the send() method.

Here's an example of how you can send an email using the send() method:

<?php
$mail->send();
?>

That's it! With these steps, you should be able to send emails using Google SMTP in your PHP script.

Important notes: