Php mail gmail

A classic topic!

To send an email using PHP and Gmail, you'll need to use the PHPMailer library, which is a popular and widely-used library for sending emails in PHP. Here's a step-by-step guide to help you get started:

Step 1: Install PHPMailer

You can install PHPMailer using Composer, a popular package manager for PHP. Run the following command in your terminal:

composer require phpmailer/phpmailer

Step 2: Configure PHPMailer

Create a new PHP file (e.g., send_email.php) and add the following code:

<?php
require 'vendor/autoload.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Set your Gmail credentials
$mail = new PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'your_password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;

// Set the email message
$mail->setFrom('[email protected]', 'Your Name');
$mail->addAddress('[email protected]', 'Recipient Name');
$mail->Subject = 'Test Email';
$mail->Body = 'This is a test email sent using PHPMailer and Gmail.';

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

Replace [email protected] and your_password with your actual Gmail credentials.

Step 3: Enable Less Secure Apps

To allow PHPMailer to connect to your Gmail account, you need to enable "Less Secure Apps" in your Google Account settings. Here's how:

  1. Go to your Google Account settings.
  2. Click on "Security" from the left-hand menu.
  3. Scroll down to the "Less secure app access" section.
  4. Toggle the switch to "On".

Step 4: Run the script

Save the send_email.php file and run it using your web server or a PHP development environment. If everything is set up correctly, you should receive an email at the recipient's email address.

That's it! You've successfully sent an email using PHP and Gmail.

Remember to always keep your Gmail credentials secure and never share them with anyone.