Send Email in PHP Using PHPMailer


Download

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

  1. Create email address and password from Cpanel
  2. 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.

Download

Facebook Official Page: All PHP Tricks

Twitter Official Page: All PHP Tricks

Article By
Javed Ur Rehman is a passionate blogger and web developer, he loves to share web development tutorials and blogging tips. He usually writes about HTML, CSS, JavaScript, Jquery, Ajax, PHP and MySQL.
  1. Thanks for this Javed. It works fine for sending to hotmail accounts but I’m having problems sending to gmail accounts. Any ideas?

    Thanks

    1. 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.

  2. 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.

  3. 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

  4. 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?

  5. 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

    1. 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.

      1. 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??

    2. 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.

  6. Great job, but please i have been looking for how i can send this to multiple emails, at once how can i do that?

      1. 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

Leave a Reply

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