How to Send Email in PHP using Gmail SMTP

send mail

Send email is a simple and straight forward task in PHP. Some beginners and sometimes even the experienced PHP developer too struggle to send an email using PHP.

In this blog we will create form and send Email using PHP and Gmail SMTP.

  1. Requirement
  2. Why Use Gmail SMTP in PHP
  3. Google Configuration to Generate App Password
  4. What is PHPMailer
  5. Directory Structure for Sending Email using Gmail SMTP
    1. PHP Code for Sending Email using Gmail SMTP
    2. HTML Form User Interface
  6. Download Full Code

Requirement

PHP 7.4
Gmail Account
PHPMailer

Why Use Gmail SMTP in PHP

PHP have own mail() function to send mail but it does not have advanced features for sending an email. For example, PHP’s mail() cannot send attachments. On other side Google’s Gmail SMTP have widely rich options.

Google Configuration to Generate App Password

An app password is a 16-digit code that gives a less secure app or device permission to access your Google Account. it is use in place of gmail password

Blow is steps to generate Google app password

Login into your gmail account

Go to link
https://myaccount.google.com/security?pli=1

Click on 2-Step Verification

Next click on “Get started” button

Next Enter Phone and Click on “NEXT” button

Enter Otp and Click “TURN ON” button

Next click below link
https://myaccount.google.com/apppasswords

Next Copy password and paste in $mail->Password field

$mail->Password = 'hrbc nfnf ghrb lirn'; // YOUR gmail app password

What is PHPMailer

There are many libraries available for PHP. If there is one library that is undoubtedly the best and the most used one, it is PHPMailer.

Some of the features of PHPMailer are,

  • Allows both plain text and HTML content in email body.
  • Allows array of email addresses for to|cc|bcc|reply-to.
  • It give Secure/MIME encryption.
  • It provide various encoding techniques binary, base64 and etc.
  • It has multiple language support.
  • It give email validation, SMTP authentication, word wrapping and more.

Directory Structure for Sending Email using Gmail SMTP

Create folder “gmail-smtp-mail”

Create file “index.php” in folder “gmail-smtp-mail”

PHPMailer library is necessary in the project. There are two different ways to include it in your project. The best way is to use the composer and add it as a dependency in the JSON file.

If you do not have have knowledge of composer or you have never used composer, do not worry. I have generated PHPMailer vendor folder for you. you can download vendor folder from here, unzip and put it inside the “gmail-smtp-mail” folder in your project.


PHP Code for Sending Email using Gmail SMTP

When we send email using Gmail SMTP make sure to set SMTPAuth as TRUE. Use your Gmail Username and Password as given below. This example code work when we click on submit button in form

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

require_once __DIR__ . '/vendor/phpmailer/src/Exception.php';
require_once __DIR__ . '/vendor/phpmailer/src/PHPMailer.php';
require_once __DIR__ . '/vendor/phpmailer/src/SMTP.php';

$success="";
if(isset($_REQUEST['submit'])) {
	
$name=	$_REQUEST['name'];
$email=	$_REQUEST['email'];
$message=	$_REQUEST['message'];
	
// passing true in constructor enables exceptions in PHPMailer
$mail = new PHPMailer(true);

try {
    // Server settings
    //$mail->SMTPDebug = SMTP::DEBUG_SERVER; // for detailed debug output
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port = 587;

    $mail->Username = 'YOUR EMAIL ADDRESS'; // YOUR gmail email
    $mail->Password = 'hrbc nfnf ghrb lirn'; // YOUR gmail app password

    // Sender and recipient settings
    $mail->setFrom('contact@webdav.in', 'WebDav');
    $mail->addAddress('contact@webdav.in', 'WebDav');
    $mail->addReplyTo('example@gmail.com', 'WebDav'); // to set the reply to

    // Setting the email content
    $mail->IsHTML(true);
    $mail->Subject = "Send email using Gmail SMTP and PHPMailer";
    $mail->Body = 'Name: '.$name.'<br><br>'.'Email: '.$email.'<br><br> Message :'.$message;
    $mail->AltBody = 'Plain text message body for non-HTML email client. Gmail SMTP email body.';

    $mail->send();
    $success=true;
} catch (Exception $e) {
    echo "Error in sending email. Mailer Error: {$mail->ErrorInfo}";
}
	
}


?>
 
$mail->Username = 'YOUR EMAIL ADDRESS'; // YOUR gmail email
$mail->Password = 'hrbc nfnf ghrb lirn'; // YOUR gmail app password

$mail->Username =’YOUR EMAIL ADDRESS’; – Specify your email address here.

$mail->Password = ‘hrbc nfnf ghrb lirn’; – Enter your gmail app password here.

 
// Sender and recipient settings
    $mail->setFrom('contact@webdav.in', 'WebDav');
    $mail->addAddress('contact@webdav.in', 'WebDav');
    $mail->addReplyTo('example@gmail.com', 'WebDav'); // to set the reply to
 

$mail->setFrom(‘contact@webdav.in’, ‘WebDav’); – This is where you insert the sender’s email address.

$mail->addAddress(‘contact@webdav.in’, ‘WebDav’); – Insert the recipient’s address here.

$mail->addReplyTo(‘example@gmail.com’, ‘WebDav’); – Informs the recipient which address they should reply to.

 
// Setting the email content
    $mail->IsHTML(true);
    $mail->Subject = "Send email using Gmail SMTP and PHPMailer";
    $mail->Body = 'Name: '.$name.'<br><br>'.'Email: '.$email.'<br><br> Message :'.$message;

$mail->IsHTML(true); – If have HTML content in mail body then need to set it to true,

$mail->Subject – Add the email subject here.

$mail->Body – It contains the mail message body. we will take name, email and message from HTML form

HTML Form User Interface

The form UI with the Name, Email and Message fields show to the user by using this HTML code.

 <!DOCTYPE html>
<html lang="en">
<head>
  <title>PHP Mail Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>

<div class="container">

<?php if( $success==true){ ?>
	<div class="alert alert-success">
  <strong>Success!</strong> Email message sent.
</div>
<?php }?>

  <h2>Send Mail</h2>
  <form action="" method="POST">
  
<div class="form-group">
      <label for="email">Name:</label>
      <input type="text" class="form-control" id="name" placeholder="Enter Name" name="name" required>
    </div>
   <div class="form-group">
      <label for="email">Email:</label>
      <input type="email" class="form-control" id="email" placeholder="Enter email" name="email" required>
    </div>
	 <div class="form-group">
      <label for="email">Message:</label>
      <textarea class="form-control" name="message" id="message" placeholder="Enter Message"></textarea>
    </div>
	
    <button type="submit" name="submit" class="btn btn-success">Submit</button>
  </form>
</div>

</body>
</html>

Download Full Code

Download

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top