Sending email is a simple and straightforward task in PHP. Yes! trust me. For some beginners and sometimes even the experienced too struggle to send an email using PHP.
Let’s solve it once forever with this article.
Sending an email with PHP’s core function mail() is simpler and the easier option.
<?php
// The message
$message = "Hi, how are you doing?";
mail('phppot@example.com', 'Email Subject', $message);
?>
This PHP’s mail function does not have advanced features for sending an email. For example, we cannot send attachments using PHP’s mail(). To send email via Google’s Gmail SMTP, we need sophisticated options.
So let us take the best and most popular route. There are so many libraries available for PHP for different purposes. If there is one library that is unarguably the best and the most used one, it is PHPMailer.
When you want to send email in a PHP contact form, you may essentially need a SMTP server. If you do not have access to a SMTP server, then you may use Google’s GMail SMTP.
Let us see how to send email in PHP using PHPMailer library via Gmail SMTP. Following is the project structure. See, the PHPMailer library is added as a dependency in the vendor folder.
We will use PHPMailer class for sending emails by using Gmail SMTP server. Some of the features of PHPMailer are,
It is important to have the PHPMailer library 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 or have never used it, I would strongly recommend you to learn composer. It is the popular dependency manager in PHP and will be quite useful.
Without composer, you can download the PHPMailer, unzip and put it inside the vendor folder in your project. In this example, I have used the same method.
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 is adapted from PHPMailer’s example script.
<?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';
// 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 = 'example@gmail.com'; // YOUR gmail email
$mail->Password = 'YOUR_GMAIL_PASSWORD'; // YOUR gmail password
// Sender and recipient settings
$mail->setFrom('example@gmail.com', 'Sender Name');
$mail->addAddress('phppot@example.com', 'Receiver Name');
$mail->addReplyTo('example@gmail.com', 'Sender Name'); // to set the reply to
// Setting the email content
$mail->IsHTML(true);
$mail->Subject = "Send email using Gmail SMTP and PHPMailer";
$mail->Body = 'HTML message body. <b>Gmail</b> SMTP email body.';
$mail->AltBody = 'Plain text message body for non-HTML email client. Gmail SMTP email body.';
$mail->send();
echo "Email message sent.";
} catch (Exception $e) {
echo "Error in sending email. Mailer Error: {$mail->ErrorInfo}";
}
?>
For setting FromEmail and FromName, we can either use SetFrom() function or use PHPMailer properties PHPMailer::From and PHPMailer::FromName. For example,
<?php
$mail->From = "from email address";
$mail->FromName = "from name";
?>
AddReplyTo(), AddAddress() functions will accept array of email addresses, and name is optional.
If we have HTML content as mail body, we need to set content body text/HTML by using,
$mail->IsHTML(true);
After setting all properties and mailer information with the PHPMailer object, PHPMailer::send() function returns TRUE on successful mail transfer and FALSE on failure.
I am not sure if it is formally approved by Google to use its SMTP
server to send email in this way. I do not see any information
prohibiting it either.
Someone just used your password to try
to sign in to your account from a non-Google app. Google blocked
them, but you should check what happened. Review your account
activity to make sure that no one else has access....
Login to your Gmail account and give confirmation that it is you.Now you can send email in PHP using Google Gmail SMTP for free. Refer to code a custom Gmail email inbox using PHP with IMAP.
Hi Vincy,
Where is class.phpmailer.php can you help me to find it?
thank you..
Hi Yogendra,
The code is updated. The download package contains the complete code and the dependency also.
Working cool, after try many different options. This code works!!! thankss
Hi,
Can you help me with troubleshooting .
I am getting error .
This page isn’t working localhost is currently unable to handle this request.
HTTP ERROR 500
Post me the trace information and I will definitely help you out.
thank you very much
Welcome Mukhtaar.
how to load it in server.when i put in server.Noting happens after clicking submit button.
Hi Athul,
Check if you have the right SMTP configuration, that is where everybody fails. You should not have the two-factor authentication enabled.
Hi,
Can i use this with localhost?
Thanks
Yes Rozanna, it will work on localhost. Try and let me know.
Hi,
Can you help me with troubleshooting .
I am getting error .
SMTP Error: Could not authenticate. Problem on sending mail
Tushar,
Set the SMTP debug constant value to 2 and you will get more details on why it is not working. Post that detail and I will help you.
can we send mails from localhost by using phpmailer?
Yes Rakesh, we can send email from localhost using Phpmailer. All we need is a SMTP server that is capable of sending emails and you need to connect to it.
Working great! Thank you Vincy.
Welcome Brad.
Its working great, thank you.
Welcome Ann.
Sorry Vincy
I am getting error
” Invalid address: RECIPIENT_EMAILYou must provide at least one recipient email address.
Problem in Sending Mail.”
Hi Alex,
Set a valid email for the recipient.
Hi,
I have used your code and it is showing “SMTP Error: Could not connect to SMTP host”
Can you please help?
Hi Subrata,
Check the last section of the article.
Of all the code available across the Internet. This is the only one working. Thanks Vincy. My respect.
Hi Petr,
Thank you for the nice words.
Hai,
I have an issue, Please, help me to reolve the below as mentioned,
Not connecting to custom mail service provided by namecheap using SMTP with PHP Mailer 2.0. Is there any problem PHP Versions?We are installing PHP 7.0.33. Please give us solution to resolve this?Eventhough we are giving correct credentials of mailserver , but it not connecting and showing the error,
Mailer Error: SMTP Error: Could not connect to SMTP host.
Hi Sujatha,
Could be due to many issues like, host, port, proxy servers, firewalls etc. You need to eliminate one by one.
Hi Vincy,
I’ve added an mobile fied in this form, can you please help me how can I post this field as well, I tried but couldn’t get success!
Thanks
Try using this https://phppot.com/php/php-contact-form/ and it has a contact form as example.
Thanks for the tutorial, I have this working but I refuse to believe that it’s standard practise to just add your email and password in a php file exposed, shouldn’t those be encrypted somehow, if so can you point me in the right direction on how to do that?
If the server is hacked all they need to do is look in to the php file to have your gmail cridentials, now you could potentially setup a gmail account to be used only from the form and nothing else but I don’t think that’s the best solution.
Hi Boyan,
Yes, I agree with you. This is for testing and development purposes. May be in production, it would be better to use your email hosting provider’s smtp. Next option is to go for a dedicated Gmail email that can be used only for this purpose.
There is an another option using which you can send email using oAuth token. I will write that in a separate tutorial.
Hi,
Can you help me with troubleshooting .
The Execute in else statement –Problem on sending mail
Hi Bharath,
Post the error trace and it will help understand the issue.
Hello,
Can you help me
My form is complited but Email not sending my Gmail Account.
Hi Viral,
You need to allow less secure apps in the Gmail side.
nice its work
Thank you Kulafu.
Can I put the latest from the PHPMailer site in dependency?
Hi Fernand,
The download zip contains the PHPMailer library also. If you wish to upgrade you can do it. No issues.
If you know composer, you can do it via that and it will be good.
dear Vincy i have managed to make it work by turning on the Less secure apps setting in going and it worked but now mails show like they have been sent from google i check the sent items.
yet the receipt is not receiving the mail.
should i upgrade my PHPmailer
Hi Albert,
Yes, since it is being sent using GMail ID, it will show like that. Check your spam folder it might have been delivered there.
Am getting problem sending email
Hi Arnold,
Post the trace to identify.
what is the code to get email with all input fields? plz help
Hi Ayisha,
Check this article https://phppot.com/php/php-contact-form/ for the contact form. It gets all input fields.
In your google account ->security->Less secure app access(turn On) and two autothentic should be off
We should set subject, content and header information. When we send email using Gmail SMTP make sure to set SMTPAuth as TRUE and SMTPSecure as tls/ssl. Use your Gmail Username and Password to send an email.
100% works
Thank you Deepak.
I got this error..
Fatal error: Class ‘PHPMailer’ not found in G:\CM Important\POS\root\abc\email.php on line 3
Hi Hussain,
Check if you have PHPMailer in the vendor folder.
Can i use any free web hosting.
Hi Sanjeev,
Yes, you can use any hosting to send email.
Hi,
Thanks for your detailed instruction. I saved inputted data to database, but got this error when sending email.
“SERVER -> CLIENT: 535-5.7.8 Username and Password not accepted. Learn more at535 5.7.8 ..”
//I checked username and password of my email and it’s working great.
Hope to receive your comment soon. Thank you.
Hi Phu,
Since you have already checked the password, try this out “Allow less secure apps: If you don’t use 2-Step Verification, you might need to allow less secure apps to access your account.”
Wooo!! i just the configuration as directed and it worked properly Thanks a lot Vincy
Welcome Barnabas. Thank you.
Please the phpmailer for gmail is not working on a live server please help me out
Hi Barnabas,
What is the issue you have? Do you get any error?
Such a talented girl are you, I’m a student and want to become a PHP developer like you, thank you very much for this article.
Thank you Amaan Warsi. Keep learning.
Hi Vincy!
First of all, many thanks for the tutorial. I have tried a few and this is the simplest one, and it works!
However, I am facing a problem that, despite having read the troubleshooting from PHPMailer Github, Stackoverflow, etc. I could not spot.
Whe I use it from localhost, the emails are sent nicely from the Gmail account. However, what it works in the localhost environment does not work from the hosting, i.e. when I upload those files into the hosting, those same files do not work anymore. The webpage freezes just before the “send” command is executed and the whole website is unavailable for 1-2 minutes.
Despite having set SMTPDebug = 2, the server does not throw any info.
I am stuck.
Any ideas?
Additional info: The hosting provider is Strato, payed and I did not find related info about blocking features for this kind of usage.
Many thanks in advance
David
Hi David,
Many hosting providers prohibit sending email via script by connecting an external smtp server.
So, what you need to do is
1) raise a ticket and check it with your hosting provider,
2) try with some other smtp server
3) try with email provided by your hosting provider and choose PHP’s mail() function as the mode.
How do people get this good!
Thanks! Heartfelt thanks!
Welcome Elero.
Super script – ça marche bien – mille bravo – mille merci
Thank you!
Please can you be my personal mentor on php. I want to get highly advanced.
Hi Williams,
I will try my best to help you.
Amazing, thanks!
Welcome Ulises.
Please help.
Got this error.
534-5.7.14 Please log in via your web browser and then try again.
Thank you.
Hi Kamarul,
Login to your Google account and see if you have got a security message and act on it.
It worked like a charm! Thanks for sharing with the community. Simple and straight forward.
Welcome :-)
Hi Vincy..
Since May 2022, “Less secure app access” Gmail account is not supported anymore. Did you have other recruitment for use PHPMailer?
Use OAuth and authenticate. I have also written an article on that.
Hello Vincy,
Thank you for your resource and knowledge. Recently Gmail has completely shut down the “less secure app” there is no off and on function. is there any other way?
Thanks
Hi Joseph,
Use OAuth and authenticate. Its working well.