Send Email in PHP Using PHPMailer
There are various ways to send email using PHP. First option is by using simple PHP Mail Function but this function does not provide more functionality such as CC, BCC, or attachment etc that we are needed now a days, solution of our problem is PHPMailer, it is the most popular PHP library used to send emails. It was initially released in 2001 after that it become a favorite choice of PHP developers to send email through it.
Steps to Send E-mail Using PHPMailer
- Create email address and password from Cpanel
- Create PHP file to send email with name index.php
1. Create email address and password from Cpanel
To create email address and password from CPanel, login to your web host cpanel.
After logged in, go to Email >> Email Accounts
In Add Email Account, create a new email with any username that you wish, here I created with username noreply and entered your desired password twice and click on Create Account button.
Now your email is created successfully, we will use this email address and its password in below PHP script to send email.
We will also need to know our host which will be required in PHPMailer, for this purpose after creating email, scroll down you will see your newly created email address below on the same page. Click on Set Up Mail Client to view your host address and other details. However mostly host uses mail.domain.com while some uses localhost or 127.0.0.1 . I will also use mail.domain.com in my host setting below.
2. Create PHP file to send email with name index.php
Below is the script in PHP which will be sending email using PHPMailer library. Click here to download PHPMailer library to include in your file. Make sure to upload this library in your web host.
PHP
<?php
$subject = "Sending Email Using PHP Mailer";
$body ='<p>Congratulations!</p>';
$body .='<p>You have successfully received an email from
<a href="https://www.allphptricks.com/">AllPHPTricks.com</a>.</p>';
// Enter Your Email Address Here To Receive Email
$email_to = "[email protected]";
$email_from = "[email protected]"; // Enter Sender Email
$sender_name = "AllPHPTricks"; // Enter Sender Name
require("PHPMailer/PHPMailerAutoload.php");
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = "mail.yourdomain.com"; // Enter Your Host/Mail Server
$mail->SMTPAuth = true;
$mail->Username = "[email protected]"; // Enter Sender Email
$mail->Password = "your_strong_password";
//If SMTP requires TLS encryption then remove comment from below
//$mail->SMTPSecure = "tls";
$mail->Port = 25;
$mail->IsHTML(true);
$mail->From = $email_from;
$mail->FromName = $sender_name;
$mail->Sender = $email_from; // indicates ReturnPath header
$mail->AddReplyTo($email_from, "No Reply"); // indicates ReplyTo headers
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AddAddress($email_to);
// If you know receiver name use following
//$mail->AddAddress($email_to, "Recepient Name");
// To send CC remove comment from below
//$mail->AddCC('[email protected]', "Recepient Name");
// To send attachment remove comment from below
//$mail->AddAttachment('files/readme.txt');
/*
Please note file must be available on your
host to be attached with this email.
*/
if (!$mail->Send()){
echo "Mailer Error: " . $mail->ErrorInfo;
}else{
echo "<div style='color:#FF0000; font-size:20px; font-weight:bold;'>
An email has been sent to your email address.</div>";
}
?>
In the above script, I have explained each step through comments with almost each line. However, I will also explain some important point here.
In $mail->Host you have to replaced mail.yourdomain.com with your website mail host.
If mail.yourdomain.com is not working in your case, you can use localhost or 127.0.0.1 You can find more information about it from your Set Up Mail Client setting.
$mail->Username and $mail->Password will be those email and password which we created in step 1.
In $mail->From and $mail->Sender must be your domain name email address therefore I am using $email_from in both places which have domain name email which we created in step 1.
If you know that recipient name then you can use it $mail->AddAddress($email_to, “Recepient Name”); otherwise we can use it $mail->AddAddress($email_to);
If you want to send email in CC or BCC you can use the following:
$mail->AddCC(‘[email protected]’); $mail->AddBCC(‘[email protected]’);
If you want to send an attachment, first you must have that file on your web host, you will need to provide its URL in here $mail->AddAttachment(‘files/readme.txt’); You can see that files/ is directory on host where readme.txt file is already uploaded which will be attached in email before sending.
Using $mail->Send(); is compulsory, otherwise email will not be sent. If you do not want to check if email sent or not, then you can simply write $mail->Send(); this will send your email. However, I am checking if email is not send then show error otherwise it will show success message.
Once you done the above steps, then open the file index.php on web browser it will send email and also print a message of success .
Now you can check your email to verify if you have received email or not.
If you have any query regarding this tutorial, you can leave you comment. I will try to give possible answer to solve your issue.
If you found this tutorial helpful, kindly share it with your friends and developer groups.
Facebook Official Page: All PHP Tricks
Twitter Official Page: All PHP Tricks
why isnt running to my end?
Can you share the error message?
Thanks for this Javed. It works fine for sending to hotmail accounts but I’m having problems sending to gmail accounts. Any ideas?
Thanks
Dear Bazza, have you check email in gmail spam folder? Sometimes due to IP issue or some other email setting issue from your hosting side, your email goes to spam, if they are going into gmail spam then you can contact your hosting provider and ask them to solve this issue.
Thank you So much Sir,
Nice explanation without any confusion.
Thank you….
You are welcome Rajendra.
Google says using this PHPMailer to send email from PHP is not secure since 2018. If you have the latest in 2021, we’d like to subscribe.
You can use the latest PHP mailer library, which you can download from PHPMailer Github.
i use xammp how is possible to create my email address?
Hi Mark, you can not create email on XAMPP, you will need to buy hosting or you can also use gmail SMTP setting for email authentication.
Hello sir, I cant find the PHPMailer/PHPMailerAutoload.php . Please help me out. Thank you sir.
Download my tutorial, it already have it.
Dear Javed,
Do you have PHP REST API code to fetch data from another platform by using token.
Thanks
Hi John, for now I do not have any such tutorial or script.
Mostly platforms provide their documentation that will help you to integrate it.
Thank You Bro You Posted Very Helpful article Thanks
Good Job 😉
Thanks for the appreciation Faiza.
Warning: stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages: error:1416F086:SSL routines:tls_process_server_certificate:certificate verify failed in C:\xampp\htdocs\forgotpass\PHPMailer\class.smtp.php on line 354
Warning: A non-numeric value encountered in C:\xampp\htdocs\project\New folder\index.php on line 27
Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting.
how can i solve this error?
You will need to create email from your cpanel and make sure you entered the correct credentials, further try to run it through your live website.
Do you have any birthday wishes employee wise in php and mysql using phpmailer.
Hi,
thank you for this tutorial
I have a problem that PHPMailer is sending every email twice? Why i don’t know tried just about everything – maybe you know of a solution?
$mail->AddAddress(); send email, kindly make sure you are not duplicating this function on same email or you are not looping the same code twice.
what about running it on localhost using xampp and gmail sir
Yes you can also test it on localhost, and it will work, i am not sure about gmail, may be gmail also work on localhost.
Hi Javed Ur Rehman,
I tried your tutorial but I am stucked on the point where you are creating email address from cPanel. When I go to ‘Email Accounts’ Section, [https://i.imgur.com/cgg0hK2.png] it says that I will need to set the MX Record for my domain to mx.domainName.com.
When I click on ‘MX Record’ button, [https://i.imgur.com/t7KL5e4.png] it says ‘No domains on my account’. [https://i.imgur.com/dDDLc78.png]
Is there a solution to send email using PHP from cPanel ??
Thanks,
Shahzaib
Hi Shahzaib, i think you should contact to your hosting company, they can help you to sort out this issue that you are facing during email account creation.
I tried your tutorial but I got this error message
“Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting“
Dear Ben, make sure that you are entering correct credentials such as $mail->Host, $mail->Username, $mail->Password. I have used my credentials, you will need to create yours and then try. If the problem is persistent you can also ask your hosting company.
Code isn’t working
Shows this error
PHP Deprecated: __autoload() is deprecated, use spl_autoload_register() instead in /***/***/***/***/PHPMailer/PHPMailerAutoload.php on line 45
What is the solution to the above problem??
Try to use the updated PHPMailer version.
Hey Ben..
You resolve this error or not?
I have similar error coming.
My $mail->Host, $mail->Username, $mail->Password is good.
But error is arise.
Thank you sir!
I finding its very long time now finally working code is found!
Thank You for Share….
You welcome Chauhan
Great job, but please i have been looking for how i can send this to multiple emails, at once how can i do that?
Thanks!
Thanks Moreno for liking my tutorials, i hope you will also love to share it. 🙂
Hi Javed Ur Rehman This is my email {‘mou***@gmail.com’}
I want to ask you about some stuff in the language PHP and Database
Please contact me or my account Facebook Mounir Boudhan