How To Send Email Using PHPMailer

PHPMailer is one of the most popular open source PHP libraries to send emails with.

In most cases, it’s an alternative to PHP’s mail() function, but there are many other cases where the mail() function is simply not flexible enough to achieve what you need. There are many advantages of using PHPMailer over mail() function –

  • PHPMailer provides an object oriented interface, whereas mail() is not object oriented.
  • Developer does not require to make $headers string which is a headache.
  • Sending attachments is much much easier.
  • PHPMailer can send alternative plaintext version of email for those email viewers which are not HTML compatible.
  • PHPMailer can use a non-local mail server (SMTP) if the developer has authentication whereas a local server is required in mail() function.

In order to use PHPMailer, we have to download its source code from this link.. PHPMailer is used by creating an PHPMailer object and using its methods to send email as shown below in the code.

In the code below, we use PHPMailer by creating a PHPMailer object and using its methods to define the contents of the mail and send the mail. User fills in his name and email id and the mail is sent to him/her. There are two files – index.php for user input and action.php for sending email using PHPmailer.

index.php

<form action="action.php" method="post" enctype="multipart/form-data">

    <label>Name</label> <br>
    <input name="name" type="text" size="30" required /><br><br>

    <label>Email Id</label> <br>
    <input name="email" type="text" size="30" required /><br><br>

    <input name="submit" type="submit" id="submit" class="submit" value="Submit" />

</form>

action.php

<?php

    // including autoloader file
    require("PHPMailer/PHPMailerAutoload.php");

    if(isset($_POST['email']) && isset($_POST['name']) ){

        $email = $_POST['email'];
        $name  = $_POST['name'];

        // Checking if email entered properly
        if(filter_var($email, FILTER_VALIDATE_EMAIL) === false || $email=="")
                echo '<h3 style="color:red;">Please enter your email id properly .</h3>';

        else{
            /**********************PHPMailer script to send mail**********************/
            //PHPMailer Object
            $mail = new PHPMailer;

            //From email address and name
            $mail->From = "tutsheap@tutsheap.com";
            $mail->FromName = "Tutsheap";

            //To address and name
            $mail->addAddress($email, $name);
            //Recipient name is optional
            // Write $mail->addAddress($email); if not using name

            //Address to which recipient will reply
            $mail->addReplyTo("tutsheap@tutsheap.com", "Reply");

            //CC and BCC - uncomment the following lines if using CC and BCC
            //$mail->addCC("abc@xyz.com");
            //$mail->addBCC("bcc@example.com");

            //Add attachment
            $mail->AddAttachment("attachment.jpg");

            //Send HTML or Plain Text email
            $mail->isHTML(true);

            //Subject of the mail
            $mail->Subject = "Sample Mail by Tutsheap";

            //Body of the mail
            $mail->Body = <<< EOF
<html><body>
Tutsheap is sharing sample email. 
<br>
<table rules="all" style="border-color: #666;" cellpadding="10">
<tr style='background: #eee;'><td><strong>Website Name</strong> </td><td>tutsheap.com</td></tr>
<tr><td><strong>Post:</strong></td><td>How to send email using PHPMailer </td></tr>
<tr style='background: #eee;'><td><strong>Description</strong> </td><td>Online tutorials library</td></tr>
</table>
</body></html>

EOF;

            //Altbody is used to display plain text message for those email viewers which are not HTML compatible
            $mail->AltBody = "To view the message, please use an HTML compatible email viewer!";

            if(!$mail->send()) 
            {
                echo '<h3 style="color:red;">Mailer Error: ' . $mail->ErrorInfo.'</h3>';
            } 
            else 
            {
                echo '<h3 style="color:green;">Message has been sent successfully</h3>';
            }



        }

    }

?>

PHPMailer Object

$mail = new PHPMailer

Creates the new object.

$mail->From()

Sets the From email address for the message. Default value is root@localhost.

$mail->FromName()

Sets the From name of the message. Default value is Root User.

$mail->addAddress()

Recipient’s address and name.

$mail->addReplyTo()

Address to which recipient will reply.

$mail->AddAttachment()

To add attachment.

$mail->isHTML(true/false)

Send HTML or plain text email.

$mail->Subject

Subject of the mail.

$mail->body

Body of the mail.

$mail->AltBody

Used to display plain text message for those email viewers which are not HTML compatible.

$mail->send()

Sends the mail.

$mail->ErrorInfo

Displays errors if any.

$mail->setLanguage()

To display error messages in some other language. For example to use Russian, we write $mail->setLanguage("ru").

Using SMTP

We can also use mail server of another host to send email but we require the SMTP authentication of that host for this. For instance, if you want to use gmail as the mail server, the you need to have a gmail account.

Here is an example of sending email through gmail’s server using your server as host for the mail script.

<?php

require("PHPMailer/PHPMailerAutoload.php");

$mail = new PHPMailer;

//Enable SMTP debugging. 
$mail->SMTPDebug = 3;                               

//Set PHPMailer to use SMTP.
$mail->isSMTP();            

//Set SMTP host name                          
$mail->Host = "smtp.gmail.com";

//Set this to true if SMTP host requires authentication to send email
$mail->SMTPAuth = true;                          

//Provide username and password     
$mail->Username = "username@gmail.com";                 
$mail->Password = "your_password_here";                           
//If SMTP requires TLS encryption then set it
$mail->SMTPSecure = "tls";                           
//Set TCP port to connect to 
$mail->Port = 587;                                   

$mail->From = "username@gmail.com";
$mail->FromName = "Full Name";

$mail->addAddress("name@example.com", "Recepient Name");

$mail->isHTML(true);

$mail->Subject = "Subject Text";
$mail->Body = "<h1>This is message in HTML</h1>";
$mail->AltBody = "This is the plain text version of the email content";

if(!$mail->send()) 
{
    echo "Mailer Error: " . $mail->ErrorInfo;
} 
else 
{
    echo "Message has been sent successfully";
}

One big advantage in using remote SMTP over localhost is that if you use PHP’s mail() function to send email with the sender’s address domain set to anything other than the local domain name (name of the server), then the recipient’s email server’s attack filters will mark it as spam. For example, if you send an email from a server with actual host name tutsheap.com with the from(sender’s) address user@yahoo.com to receipient address user@gmail.com, then Gmail’s servers will mark it as spam or display a message to the user not to trust the email because the mail’s origin is tutsheap.com and yet it presents itself as if coming from yahoo.com. Although you own user@yahoo.com, there is no way for Gmail to find that out. PHPMailer removes this ambiguity.

Index page

Index page

Email successfully sent message

Email successfully sent

Email screenshot

Email screenshot

Body of the mail received

Email Body

Please feel free to download the source code for reference. In the demo, please wait for some time for receiving email. Also, if you do not receive the mail, then check your spam folder.

View Demo Download source

This content has been helpful to you?

Thanks for contributing!

Yes No
  • Shainaz Shaik

    <?php

    require("PHPMailer/PHPMailerAutoload.php");

    if(isset($_POST['email']) && isset($_POST['name']) ){

    $email = $_POST['email'];
    $name = $_POST['name'];

    if(filter_var($email, FILTER_VALIDATE_EMAIL) === false || $email=="")
    echo 'Please enter your email id properly .’;

    else{

    //PHPMailer Object
    $mail = new PHPMailer;

    //From email address and name
    $mail->From = “shainaz@tranquilwebsolutions.com”;
    $mail->FromName = “shainaz”;

    //To address and name
    $mail->addAddress($email, $name);
    //Recipient name is optional
    // Write $mail->addAddress($email); if not using name

    //Address to which recipient will reply
    $mail->addReplyTo(“shainaz@tranquilwebsolutions.com”, “Reply”);

    //CC and BCC – uncomment the following lines if using CC and BCC
    //$mail->addCC(“abc@xyz.com”);
    //$mail->addBCC(“bcc@example.com”);

    //Add attachment
    $mail->AddAttachment(“attachment.jpg”);

    //Send HTML or Plain Text email
    $mail->isHTML(true);

    //Subject of the mail
    $mail->Subject = “Sample Mail by shainaz”;

    //Body of the mail
    $mail->Body = <<< EOF

    Tutsheap is sharing sample email.

    Website Name tranquilcrm.com
    Post:How to send email using PHPMailer
    Description Online tutorials library

    EOF;

    //Altbody is used to display plain text message for those email viewers which are not HTML compatible
    $mail->AltBody = “To view the message, please use an HTML compatible email viewer!”;

    if(!$mail->send())
    {

    echo ‘Mailer Error: ‘ . $mail->ErrorInfo.”;
    }
    else
    {
    echo ‘Message has been sent successfully’;
    }

    }

    }

    ?>
    its not working can u plz help me

    • Vaibhav Goyal

      Please state the exact error that you got with an image if possible.

  • Shainaz Shaik

    can u plz tell me wer is the mistake

  • Shainaz Shaik

    i just replace my email id instead of u r email but i got a error