How to send mail using google smtp server with php

To send mail using Google's SMTP server with PHP, you'll need to follow these steps:

Step 1: Enable Less Secure Apps

To allow PHP to send mail using your Google 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 menu.
  3. Scroll down to the "Less secure app access" section.
  4. Toggle the switch to "On".

Step 2: Set up your PHP script

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

<?php
// Set your Google account credentials
$gmail_username = '[email protected]';
$gmail_password = 'your_password';

// Set the recipient's email address
$to_email = '[email protected]';

// Set the subject and message
$subject = 'Test email from Google SMTP';
$message = 'This is a test email sent using Google SMTP';

// Set the SMTP server details
$smtp_server = 'smtp.gmail.com';
$smtp_port = 587;
$smtp_timeout = 30;

// Create a new PHPMailer object
$mail = new PHPMailer();

// Set the SMTP server details
$mail->isSMTP();
$mail->Host = $smtp_server;
$mail->Port = $smtp_port;
$mail->SMTPAuth = true;
$mail->Username = $gmail_username;
$mail->Password = $gmail_password;
$mail->SMTPSecure = 'tls'; // or 'ssl' if you prefer

// Set the sender's email address
$mail->From = $gmail_username;

// Set the recipient's email address
$mail->addAddress($to_email);

// Set the subject and message
$mail->Subject = $subject;
$mail->Body = $message;

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

Step 3: Install PHPMailer (if you haven't already)

If you haven't already, install PHPMailer using Composer:

composer require phpmailer/phpmailer

Step 4: Run the script

Run the sendmail.php script using your web server or a PHP CLI tool like php sendmail.php.

Troubleshooting tips

By following these steps, you should be able to send mail using Google's SMTP server with PHP.