How to Send Email To Gmail Using PHPMailer in PHP

By CampCodes Administrator

Updated on:

How to Send Mail To Gmail Using PHPMailer

Tutorial: How to Send Email To Gmail Using PHPMailer in PHP

About How to Send Email To Gmail Using PHPMailer in PHP

This is a tutorial on How to Send Email To Gmail Using PHPMailer in PHP. PHP is a server-side scripting language designed primarily for web development. Using PHP, you can let your user directly interact with the script and easily to learned its syntax. It is mostly used by a newly coders for its user-friendly environment.

The PHP mail() function usually sends via a local mail server, typically fronted by a sendmail binary on Linux, BSD, and macOS platforms, however, Windows usually doesn’t include a local mail server; PHPMailer’s integrated SMTP client allows email sending on all platforms without needing a local mail server.

Now, let’s do coding.

Getting Started:

First you have to download & install XAMPP or any local server that run PHP scripts. Here’s the link for XAMPP server https://www.apachefriends.org/index.html.

And, this is the link for the bootstrap that i used for the layout design https://getbootstrap.com/.

Installing the PHPMailer

Using Composer

If you dont’ have a composer installed on your machine you can get it here, https://getcomposer.org/download/

First, Create a file that will receive the phpmailer file, write these code inside the text editor and save it as composer.json.

{
     "phpmailer/phpmailer": "~6.0"
}

Then, open your command prompt and cd to your working directory. After that, type this command and hit enter afterward.

composer require phpmailer/phpmailer

After installation you will see a different directory inside your working directory, namely vendor, etc.

READ ALSO:   How to Create a Barcode in PHP

Without Composer

To manually install the phpmailer to your app, first download the file here https://github.com/PHPMailer/PHPMailer

After you finish downloading the file, move the file inside the directory that you are working on. Now you’re ready to use the phpmailer.

Creating The Interface

This is where we will create a simple form for our application. To create the forms simply copy and write it into your text editor, then save it as index.php.

<?php session_start()?>
<!doctype html>
<html lang="en">
	<head>
		<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
		<link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
	</head>
<body>
	<nav class="navbar navbar-default">
		<div class="container-fluid">
			<a class="navbar-brand" href="https://campcodes.com">CampCodes</a>
		</div>
	</nav>
	<div class="col-md-3"></div>
	<div class="col-md-6 well">
		<h3 class="text-primary">PHP - Send Mail To Gmail Using PHPMailer</h3>
		<hr style="border-top:1px dotted #ccc;"/>
		<div class="col-md-3"></div>
		<div class="col-md-6">
			<form method="POST" action="send_email.php">
				<div class="form-group">
					<label>Email:</label>
					<input type="email" class="form-control" name="email" required="required"/>
				</div>
				<div class="form-group">
					<label>Subject</label>
					<input type="text" class="form-control" name="subject" required="required"/>
				</div>
				<div class="form-group">
					<label>Message</label>
					<input type="text" class="form-control" name="message" required="required"/>
				</div>
				<center><button name="send" class="btn btn-primary"><span class="glyphicon glyphicon-envelope"></span> Send</button></center>
			</form>
			<br />
			<?php
				if(ISSET($_SESSION['status'])){
					if($_SESSION['status'] == "ok"){
			?>
						<div class="alert alert-info"><?php echo $_SESSION['result']?></div>
			<?php
					}else{
			?>
						<div class="alert alert-danger"><?php echo $_SESSION['result']?></div>
			<?php
					}
 
					unset($_SESSION['result']);
					unset($_SESSION['status']);
				}
			?>
		</div>
	</div>
</body>
</html>

Creating the Main Function

This is the main function of the application. This code will send requests via phpmailer to be able to send mail to google SMTP. To do that copy and write these inside the text editor, then save it as send_email.php.

Note:

To make this script work without composer, make sure you change this code:

require 'vendor/autoload.php';

Into this:

require 'path/to/PHPMailer/src/Exception.php';
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';

So that it will recognize the phpmailer class when you call it in the code.

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
 
session_start();
 
if(isset($_POST['send'])){
 
    $email = $_POST['email'];
    $subject = $_POST['subject'];
    $message = $_POST['message'];
 
 
    //Load composer's autoloader
    require 'vendor/autoload.php';
 
    $mail = new PHPMailer(true);                            
    try {
        //Server settings
        $mail->isSMTP();                                     
        $mail->Host = 'smtp.gmail.com';                      
        $mail->SMTPAuth = true;                             
        $mail->Username = '1dummy2020@gmail.com';     
        $mail->Password = 'bermzwhiteknight8';             
        $mail->SMTPOptions = array(
            'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
            )
        );                         
        $mail->SMTPSecure = 'ssl';                           
        $mail->Port = 465;                                   
 
        //Send Email
        $mail->setFrom('1dummy2020@gmail.com');
 
        //Recipients
        $mail->addAddress($email);              
        $mail->addReplyTo('1dummy2020@gmail.com');
 
        //Content
        $mail->isHTML(true);                                  
        $mail->Subject = $subject;
        $mail->Body    = $message;
 
        $mail->send();
 
       $_SESSION['result'] = 'Message has been sent';
	   $_SESSION['status'] = 'ok';
    } catch (Exception $e) {
	   $_SESSION['result'] = 'Message could not be sent. Mailer Error: '.$mail->ErrorInfo;
	   $_SESSION['status'] = 'error';
    }
 
	header("location: index.php");
 
}
?>

Note: To be able to send a mail to Gmail, make sure you provide your own Gmail username and password or much better is to make a dummy account to use.

READ ALSO:   Submit Form using AJAX in PHP/MySQLi

Inside your Google account make sure you allow the less secure apps so that you can have permission to send the email.

How to Send Mail To Gmail Using PHPMailer

There you have it we successfully created a Send Mail To Gmail Using PHPMailer. I hope that this simple tutorial helps you with your projects. For more updates and tutorials just kindly visit this site.

Output

how to send email to gmail using phpmailer
how to send email to gmail using phpmailer

DEMO


Related Tutorials: Sending Email with Attachment using PHPMailer in PHP, Send POST Request Using Ajax in PHP, Submit Form using AJAX in PHP/MySQLi

Download Here

3 thoughts on “How to Send Email To Gmail Using PHPMailer in PHP”

Leave a Comment