Send Email in PHP using PHPMailer and Gmail
Updated: 30-Oct-2023 / Tags: PHP Tutorials / Views: 3796 - Author: George
Introduction
Want to send emails with PHP effortlessly? You're in the right place! In this post, we'll show you how to use PHPMailer and Gmail's SMTP server to make sending emails an easy job.
Quick Answer
- Go to Github and download the PHPMailer zip file. PHPMailer github
- Extract the zip file and copy the PHPMailer folder in your projects root directory.
-
To use Gmail as your SMTP Mail server you have to create a 16 digit Google app-password.
To create an app password, you need 2-Step Verification on your Google Account.
Go to Google Help and follow the instructions. It is simple and easy. - Create a php file in your root directory and name it send-mail.php.
- Copy and paste the simple example from the PHPMailer Github page in the send-mail.php file.
- Change the mailhost to: $mail->Host = 'smtp.gmail.com';
- The username to: $mail->Username = 'YourEmail@gmail.com';
- And the password to: $mail->Password = 'Your 16 digit Goggle app password'; that you have created in step 3.
- And you are good to go.
If this is covering you, that is awesome, but if not i have created a live demo so you can see for yourself the working code in action. And then we are going to recreate it.
Live Example
Send an email to yourself. Use a real email, don't worry your email is not stored or shared.
In this live demo i am using Gmail's SMTP server to send the email.
Okay, now that you saw that the email form is working let's re-create the whole application.
Project's folder
First of all let's see the files that we need.
Go to Github and download the PHPMailer zip file.
PHPMailer github
and extract the files in the project's root folder.
If the downloaded directory has a name of
PHPMailer-master or
something else, rename it to PHPMailer, so the name matches the
directory name of this tutorial.
Next create the file structure that you see bellow.
/-- root /-- PHPMailer -- config.php -- index.php -- script.php -- styles.css
Create a Google app password
Before we start coding, and in order to use Gmail as your SMTP Mail server you have to create a 16 digit Google app-password.
To create an app password, you need 2-Step Verification on your Google Account.
Go to Google Help and follow the instructions. It is simple and easy.
Store your app-password so you can use it in later in this tutorial where we creating the config.php file.
The styles.css file
Let's first create the styles.css file. Copy and paste the css code in the css file so when we code the html form, the styles are already applied.
I will not go through and explain the css code. Everything is basic css and also it is not important for this tutorial.
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body{
font-family: sans-serif;
min-height: 100%;
color: #555;
}
form{
max-width: 400px;
margin: 50px auto 0 auto;
border: thin solid #e4e4e4;
padding: 20px;
box-shadow: 0 5px 5px rgba(0, 0, 0, 0.2);
}
form .info{
font-weight: bold;
margin-bottom: 30px;
text-align: center;
font-size: 24px;
}
form label{
display: block;
margin-bottom: 10px;
padding-left: 5px;
}
form input, form textarea{
display: block;
width: 100%;
padding: 10px;
margin-bottom: 10px;
font-size: 16px;
border: thin solid #e4e4e4;
margin-bottom: 30px;
}
form input:focus,
form select:focus,
form textarea
{
outline: none;
}
form textarea{
min-height: 80px;
}
form input::placeholder{
font-size: 16px;
}
form button{
background: #32749a;
color: white;
border: none;
padding: 15px;
width: 100%;
font-size: 16px;
margin-top: 20px;
cursor: pointer;
}
form button:active{
background-color: green;
}
.error{
margin-top: 30px;
color: #af0c0c;
}
.success{
margin-top: 30px;
color: green;
}
The index file
In the index.php file we are going to create a simple HTML page layout.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>Send Email in PHP using PHPMailer and Gmail</title>
</head>
<body>
<!-- Here goes the html email form -->
</body>
</html>
The HTML Email Form
Again our html form is simple and basic. We have two input fields, one for the email and one for the subject. And a textarea, to type the message, and a submit button.
<form action="" method="post" enctype="multipart/form-data">
<div class="info">
Send an email to your self
</div>
<label>Enter your email</label>
<input type="email" name="email" value="">
<label>Enter a subject</label>
<input type="text" name="subject" value="">
<label>Enter your message</label>
<textarea name="message"></textarea>
<button type="submit" name="submit">Submit</button>
</form>
The form will submit to the same page because we leave the action attribute empty. action="".
Now it's time to write the php code.
The config.php file
In the config.php file we will define the values that we will use in the PHPMailer object.
<?php
// Define the Gmail smtp server
define('MAILHOST', "smtp.gmail.com");
// Define as a username the email that you use in your Gmail account.
define('USERNAME', "YourEmail@gmail.com");
// Define your 16 digit Gmail app-password.
define('PASSWORD', "Your 16 digit Google app password");
// Define the email address from which the email is sent.
define('SEND_FROM', "email@your-domain.com");
// Define the name of the website from which the email is sent.
define('SEND_FROM_NAME', "My Website");
// Define the reply-to address.
define('REPLY_TO', "email@your-domain.com");
// Define the reply-to name.
define('REPLY_TO_NAME', "Your name");
To make things easier i will share my config file, this is the one that i use in the live demo, but without my 16 digit Google app-password.
<?php
// Define the Gmail smtp server
define('MAILHOST', "smtp.gmail.com");
// Define as a username the email that you use in your Gmail account.
define('USERNAME', "digitalfox.tutorials@gmail.com");
// Define your 16 digit Gmail app-password.
define('PASSWORD', "My 16 digit Google app password");
// Define the email address from which the email is sent.
// This email belongs to my website, it has nothing to do with Gmail.
define('SEND_FROM', "info@digitalfox-tutorials.com");
// Define the name of the website from which the email is sent.
define('SEND_FROM_NAME', "Digitalfox-tutorials");
// Define the reply-to address.
define('REPLY_TO', "info@digitalfox-tutorials.com");
// Define the reply-to name.
define('REPLY_TO_NAME', "George");
I hope you get the idea how to define your Google account settings because i have seen many people are struggling with this.
Creating the script.php file
In the script.php file we are going to write a function named sendMail() that captures the values from the
html form and send the email to the email address that we type in the form.
We will call the function in the index.php file before the HTML code.
<?php
/**
* We have to put the PHPMailer namespaces at the top of the page.
*/
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
/*
We have to require the config.php file to use our
Gmail account login details.
*/
require 'config.php';
/**
We have to require the path to the PHPMailer classes.
*/
require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
/**
* The function uses the PHPMailer object to send an email
* to the address we specify.
* @param [string] $email, [Where our email goes]
* @param [string] $subject, [The email's subject]
* @param [string] $message, [The message]
* @return [string] [Error message, or success]
*/
function sendMail($email, $subject, $message){
// Creating a new PHPMailer object.
$mail = new PHPMailer(true);
// If you want to see the email process uncomment the
// SMTPDebug property.
// $mail->SMTPDebug = SMTP::DEBUG_SERVER;
// Using the SMTP protocol to send the email.
$mail->isSMTP();
/*
Setting the SMTPAuth property to true, so we can use
our Gmail login details to send the mail.
*/
$mail->SMTPAuth = true;
/*
Setting the Host property to the MAILHOST value
that we define in the config file.
*/
$mail->Host = MAILHOST;
/* Setting the Username property to the USERNAME value
that we define in the config file.
*/
$mail->Username = USERNAME;
/*
Setting the Password property to the PASSWORD value
that we define in the config file.
*/
$mail->Password = PASSWORD;
/*
By setting SMTPSecure to PHPMailer::ENCRYPTION_STARTTLS,
we are telling PHPMailer to use the STARTTLS encryption
method when connecting to the SMTP server.
This helps ensure that the communication between your
PHP application and the SMTP server is encrypted, adding a
layer of security to your email sending process.
*/
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
// TCP port to connect with the Gmail SMTP server.
$mail->Port = 587;
/*
Who is sending the email. Again we use the constants
that we define in the config file.
*/
$mail->setFrom(SEND_FROM, SEND_FROM_NAME);
/*
Where the mail goes. We use the $email function's
parameter that holds the email address that we type
in the email input field.
*/
$mail->addAddress($email);
/*
The 'addReplyTo' property specifies where the
recipient can reply to.
Again we use the constants from the config file.
*/
$mail->addReplyTo(REPLY_TO, REPLY_TO_NAME);
/*
By setting $mail->IsHTML(true), we inform PHPMailer that
the email message we're constructing will include
HTML markup.
This is important when we want to send emails with
HTML formatting, which allow us to include things like
hyperlinks, images, formatting,
and other HTML elements in our email content.
*/
$mail->IsHTML(true);
/*
Assigning the incoming subject to the
$mail->subject property.
*/
$mail->Subject = $subject;
/*
Assigning the incoming message to the $mail->body property.
*/
$mail->Body = $message;
/*
When we set $mail->AltBody, we are providing
a plain text alternative to the HTML version of our email.
This is important for compatibility with email clients
that may not support or display HTML content.
In such cases, the email client will display
the plain text content instead of the HTML content.
*/
$mail->AltBody = $message;
/*
And last we send the email.
If something goes wrong the function will return an error,
else the function returns the string success.
We are going to catch the returned value in the index file,
and display it in the HTML form.
*/
if(!$mail->send()){
return "Email not send. Please try again";
}else{
return "success";
}
}
Back to the index.php file
Now we go back to the index file and add the following php code at the top of the file.
<?php require("script.php"); ?>
<?php
if(isset($_POST['submit'])){
if(empty($_POST['email']) || empty($_POST['subject']) || empty($_POST['message'])){
$response = "All fields are required";
}else{
$response = sendMail($_POST['email'], $_POST['subject'], $_POST['message']);
}
}
?>
<!DOCTYPE html>
- In line 1 we require the script.php file so we access the sendMail() function.
- In line 3 we check if the form is submitted.
- In line 4 we check if all fields have values. If not, we assign in a variable named $response a message that: All fields are required.
- In line 7 and if our input fields have values, we call the sendMail() function and we pass-in as arguments the values that the form sends with the POST request. And we store the returned value in the $response variable.
Now we have to go to the HTML form to catch and display whatever the sendMail() function returns.
Back to the HTML form
We are back to the HTML form and we are going to add under the submit button an if statement in line 28.
We are checking the $response variable. If the $response variable holds the string 'success', we are going to display the success message. Else we are going to display the error that the sendMail() function returns.
<button type="submit" name="submit">Submit</button>
<?php
if(@$response == "success"){
?>
<p class="success">Email send successfully</p>
<?php
}else{
?>
<p class="error"><?php echo @$response; ?></p>
<?php
}
?>
And that's it! This is all the code you need to use PHPMailer and Gmail for sending emails in PHP.
Conclusion
In conclusion, we saw how to send emails in PHP using the PHPMailer library and Gmail's SMTP server. We discussed the necessity of creating a Google app password to use Gmail as your mail server and learned how to integrate your Gmail account details with PHPMailer. With this knowledge, you're now ready to send emails through PHP applications using PHPMailer and Gmail SMTP.
Also we saw how to write an HTML form and a PHP function to use the PHPMailer library.
Last Words
Thanks for reading, i hope you find the article helpful.
Please leave a comment if you find any errors, so i can update the page with the correct code.
Source code
If you feel like avoiding all the copying and pasting, you can buy me a coffee and get the source code in a zip file. Get the source code
Comment section
You can leave a comment, it will help me a lot.
Or you can just say hi. 😉