SIGN UP LOGIN
PHP

Send email in PHP from SMTP server using PHPMailer

  14th Apr, 2020   Rahul Ranjan   0 comment
Send email in PHP from SMTP server using PHPMailer

In this article, we are going to learn how to send Email from SMTP server using PHPMailer. If we talk about PHP, there are several libraries available to send E-mail. But PHPMailer is most widely used library in PHP to send E-mail .

Why to use PHPMailer?

PHPMailer provides many advantages over PHP's default mail() function. There is no need to create headers seperately in PHPMailer. It also supports SMTP protocol and provides authentication over TLS and SSL. It supports both Plain text and HTML mail format.

So, here we will create a form which will accept some input from user and then we will add those inputs into our Mail template and will deliver it to the receiver's email address. You can see the demo of this article by clicking demo button available below: 

Demo

Let us get started. Firstly download the PHPMailer library by Clicking here .

Now we will create a simple html form to accept user input.


<form id="detail_submit" action="" method="post">
 <label>Field marked with (<font color="red">*</font>) are important and required.</label>
 <span>Name<font color="red">*</font>:</span>
 <input name="name" type="text" placeholder="Enter your name" value="<?php echo $name;?>"/><br>
 <span>Email<font color="red">*</font>:</span>
 <input name="email" type="text" placeholder="Enter your email" value="<?php echo $email;?>"/><br>
 <span>Message<font color="red">*</font>:</span>
 <textarea name="message" placeholder="Enter your message"><?php echo $message;?></textarea><br>
 <input name="submit_response" type="submit" value="Send" />
</form>

Here in above code, we have created a form which will accept user's name, email and message. Now we will create a method for sending mails using PHPMailer. Create a file named sendMail.php inside PHPMailer folder and paste content below:

sendMail.php


<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'src/Exception.php';
require 'src/PHPMailer.php';
require 'src/SMTP.php';
function send_smtp_mail($subject,$message,$replyMail,$replyName,$fromMail,$fromName,$toEmail,$toName,$host,$username,$password,$smtpMode="tls",$smtpPort="587"){
    $mail = new PHPMailer;
 $mail->isSMTP(); // Set mailer to use SMTP
 $mail->Host = $host; // Specify main and backup SMTP servers
 $mail->SMTPAuth = true; // Enable SMTP authentication
 $mail->SMTPDebug = 0;//0 = off (for production use) - 1 = client messages - 2 = client and server messages
 $mail->Username = $username; // SMTP username
 $mail->Password = $password; // SMTP password
 $mail->SMTPSecure = $smtpMode; // Enable TLS encryption, `ssl` also accepted
 $mail->SMTPOptions = array(
  'ssl' => array(
   'verify_peer' => false,
   'verify_peer_name' => false,
   'allow_self_signed' => true
  )
 );
 $mail->Port = $smtpPort;                                    // TCP port to connect to
 $mail->setFrom($fromMail,$fromName);
 $mail->addAddress($toEmail, $toName);     // Add a recipient
 $mail->addReplyTo($replyMail, $replyName);
 $mail->isHTML(true);                                  // Set email format to HTML
 $mail->Subject = $subject;
 $mail->msgHTML($message); //$mail->msgHTML(file_get_contents('contents.html'), __DIR__); //Read an HTML message body from an external file, convert referenced images to embedded,
 $mail->AltBody = 'HTML messaging not supported';
 if(!$mail->send()) {
    echo 'Message could not be sent.';
    return 'Mailer Error: ' . $mail->ErrorInfo;
 } else {
    //echo 'Message has been sent';
 }
}
?>

In above code we have created a method named send_smtp_mail() which will accept all important parameters required to initiate and authenticate SMTP connection. After SMTP authentication the email is delivered to the recipient.

Now we will make a Html E-mail template to provide standard look to the message before sending mail to be sent to the recipient. Copy and paste below code into a file and name it as template.form.php .

template.form.php


<?php
function form_response($name,$content){
 return '<html>
    <body>
    <table width="100%" border="0" cellspacing="0" cellpadding="0" bgcolor="#f2f2f2">
    <tbody>
     <tr>
      <td>
       <table width="650" border="0" bgcolor="#fff" cellspacing="0" cellpadding="0" align="center" style="font-family:Arial,Helvetica,sans-serif;">
        <tr>
         <td colspan="2" style="padding:15px 0;"><center><a href="https://7topics.com" rel="noreferrer"><img style="width:160px;" src="https://cdn.7topics.com/content/image/7topics_logo_272x67.png" alt="" border="0"></a></center></td>
        </tr>
        <tr>
         <td height="1" bgcolor="#d6d6d6" style="font-size:1px;line-height:1px"></td></tr>
        <tr>
        <tr>
         <td height="25"></td></tr>
        <tr>
        <tr>
         <td>
          <table width="620" border="0" bgcolor="#fff" cellspacing="0" cellpadding="0" align="center" style="color:#666;font-size:14px;line-height:34px;">
          <tr>
           <td colspan="2" style="font:bold 14px Arial,Helvetica,sans-serif;">Dear '.explode(" ",$name)[0].',</td>
          </tr>
          <tr>
           <td height="8"></td>
          </tr>
          <tr>
           <td style="font-weight:bold;">
            Thank you for getting in touch!
           </td>
          </tr>
          <tr>
           <td>
            You have successfully submitted your response to 7topics.com
           </td>
          </tr>
          <tr>
           <td>
            <table style="color:#666;font-size:14px;line-height:34px;">
            <tr>
             <td style="font-weight:bold">Details received:</td>
            </tr>
            <tr>
             <td>Name : '.$name.'</td>
            </tr>
            <tr>
             <td>Purpose : Email Testing</td>
            </tr>
            <tr>
             <td>Content : '.$content.'</td>
            </tr>
            </table>
           </td>
          </tr>
          <tr>
           <td height="10"></td>
          </tr>
          <tr>
           <td style="color:#666;font-size:14px;line-height:34px;">
            Have a great day!
           </td>
          </tr>
          <tr>
           <td height="15"></td>
          </tr>
          <tr>
           <td style="color:#666;font-size:14px;line-height:24px;"><b>Best Regards,</b><br>
           <b>7topics Team</b></td>
          </tr>
          </table>
         </td>
        </tr> 
        <tr>
         <td height="20"></td>
        </tr> 
        <tr>
         <td height="1" bgcolor="#d6d6d6"></td>
        </tr>
        <tr>
         <td bgcolor="" height="50" valign="middle">
          <table width="100%" border="0" cellspacing="0" cellpadding="0">
          <tbody>
          <tr>
          <td width="25"></td>
          <td width="505" style="color:#696868;font-family:Arial,Helvetica,sans-serif;font-size:12px;">For any query, please do contact us at <a href="mailto:support@7topics.com?cc=rahulcoolranjan@gmail.com" style="color:#03A9F4;text-decoration:none" target="_blank" rel="noreferrer">support@7topics.com</a></td>
          </tr>
          </tbody>
          </table>
         </td>
        </tr>
       </table>
      </td>
     </tr>
    </tbody>
    </table>
    </body>
   </html>';
}
?>

Now we are done with setting up out PHPMailer, so now we need to write the code to process the form and send email to the user. Below i have given the code to send the user input to the user's email.


<?php
/*Setting variable default value*/
$name="";
$email="";
$message="";
$error=0;
$success=0;
$error_msg="";
/* Handling form submission */ 
if(isset($_POST["submit_response"])){
 include "templates/template.form.php";
 include "PHPMailer/sendMail.php";
 $name=$_POST["name"];
 $email=$_POST["email"];
 $message=$_POST["message"];
 if($name=="" || $email=="" || $message=="")  {
  $error_msg="Please fill all fields";
  $error=1;
 }elseif(!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) {
  $error_msg="Invalid Email. Please recheck your email.";
  $error=1;
 }
 if($error!=1){
  $success=1;
  $subject="Testing Mail - 7topics";
  $message=form_response($name,$message);
  
  //SMTP Mail Configuration
  $SMTP_HOST="mail.site.com";//Ex:-mail.site.com
  $SMTP_MODE="ssl";//Ex:- tls
  $SMTP_PORT="465";//Ex:- 587
  $USER_NAME="Support";
  $USER_EMAIL_ADDR="name@mail.com"; //SMTP Email Id
  $USER_EMAIL_PASS="password"; //SMTP Email Password
  send_smtp_mail($subject,$message,$USER_EMAIL_ADDR,$USER_NAME,$USER_EMAIL_ADDR,$USER_NAME,$email,$name,$SMTP_HOST,$USER_EMAIL_ADDR,$USER_EMAIL_PASS,$SMTP_MODE,$SMTP_PORT);
  //Reseting form value after submission.
  $name=$email=$message="";
 }
}
?>

In above code we are checing and validating user's input. After successfull validation the data is sent to the user's email using send_smtp_mail() function. In order to send email set value for $SMTP_HOST, $SMTP_MODE, $SMTP_PORT, $USER_NAME, $USER_EMAIL_ADDR, $USER_EMAIL_PASS. The complete source code for the above article can be downloaded using button below:

Download

Thank you for reading my article, i hope that you liked this article. For any doubts or any request you can put your important feedback in the comment box below.

Rahul Ranjan
Author: Rahul Ranjan

Founder of 7topics. Rahul Ranjan is a website developer and blogger who loves to read and share about new techonology with others through his blog.

SUBSCRIBE TO NEWSLETTER

Enter your email address to subscribe to this blog and receive notifications of new posts by email

RECENT POSTS

1