PHP send email for Forgot Password

Ren picture Ren · Jun 17, 2013 · Viewed 33.9k times · Source

So I am building a localhost page, and it contains users, so I created a forgot password page to reset password if they forget, and to update the randomized password into the database.

This is the codes for ForgotPassword, and I use it by validating email and not ID.

<h2 style="text-align:center;"> Forgot Password </h2>
<table align="center" bgcolor="#FFFFFF" width="500" height ="180">
<form action="doForgotPassword.php" method="post">
            <tr><td align="right" height="50" width="200">First Name</td>
                <td><input type="text" name="first_name" /></td></tr>

            <tr><td align="right" height="50">Email</td>
                <td><input type="text" name="email" /></td></tr>

            <tr><td colspan="2" align="right"><input type="submit" value="Submit"/></td></tr>

        </table> </form> </td></table>

And this is the codes for DoForgotPassword, I managed to change it in the database but not able to email the user. I am having trouble at this line

    <?php
    public function sendMail($email =$_POST['email'] , $id)

This is the rest of the codes after it.

    {
$to = $email /* separated by comma for another email (useful if you want to keep records(sending to yourself))*/;
$subject = 'INSERT_SUBJECT_HERE';

$bound_text = "----*%$!$%*";
$bound = "--".$bound_text."\r\n";
$bound_last = "--".$bound_text."--\r\n";

$headers = "From: [email protected]\r\n";
$headers .= "MIME-Version: 1.0\r\n" .
        "Content-Type: multipart/mixed; boundary=\"$bound_text\""."\r\n" ;

$message = " you may wish to enable your email program to accept HTML \r\n".
        $bound;

$message .=
'Content-Type: text/html; charset=UTF-8'."\r\n".
'Content-Transfer-Encoding: 7bit'."\r\n\r\n".
'

        <font size="3" color="#000000" style="text-decoration:none;font-family:Lato light">
        <div class="info" Style="align:left;">

        <p>information here<!--(im sure you know how to write html ;))--></p>

        <br>

            '. /* <p>Charge:    '.$charge.'    </p> */'
        <br>

            <p>Reference Number: '.$id.'</p>

                        </div>

        </br>
        <p>-----------------------------------------------------------------------------------------------------------------</p>
        </br>
        <p>( This is an automated message, please do not reply to this message, if you have any queries please contact [email protected] )</p>
        </font>
        </div>
        </body>
    '."\n\n".
                                                                $bound_last;

        $sent = mail($to, $subject, $message, $headers); // finally sending the email


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


        function createRandomPassword() {
        $chars = "ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz0123456789";
        $i = 0;
        $pass = '' ;

        while ($i <= 8) {
            $num = mt_rand(0,61);
            $tmp = substr($chars, $num, 1);
            $pass = $pass . $tmp;
            $i++;
        }
        return $pass;
        }

        $pw = createRandomPassword();
        $query = "UPDATE users SET password= SHA1('$pw') WHERE email = '$email' ";
        $result = mysqli_query($link, $query);
          if ($result){
          $query3 = "SELECT * FROM users where email = '$email'";
        $sql = mysqli_query($link, $query3) or die(mysqli_error());  
       $rownum = mysqli_num_rows($sql);

         if(!$rownum  ) {
     echo "We can not find your email in our records";
        }

       }

And this is the resulting code

     if($result){

         if(isset($_POST['id'])){
           $id = $_POST['id'];

   sendMail($email, $id);

           }
         }
                ?>

Answer

Steve P picture Steve P · Jun 17, 2013

This is the function I use for any mail I do on my current application (sensitive info removed), it's pretty easy to figure out what you need to do but the comments provided, should answer some questions,

This function allows for html formatting which should allow you to make it prettyful :D

public function sendMail($email, $company, $location, $startAt, $endAt, $date, $userId,$duration)
{
    $to = $email; /* '. ',';  separated by comma for another email (useful if you want to keep records(sending to yourself))*/;
    $subject = 'INSERT_SUBJECT_HERE';

    $bound_text = "----*%$!$%*";
    $bound = "--".$bound_text."\r\n";
    $bound_last = "--".$bound_text."--\r\n";

    $headers = "From: [email protected]\r\n";
    $headers .= "MIME-Version: 1.0\r\n" .
            "Content-Type: multipart/mixed; boundary=\"$bound_text\""."\r\n" ;

    $message = " you may wish to enable your email program to accept HTML \r\n".
            $bound;

    $message .=
    'Content-Type: text/html; charset=UTF-8'."\r\n".
    'Content-Transfer-Encoding: 7bit'."\r\n\r\n".
    '
<!-- here is where you format the email to what you need, using html you can use whatever style you want (including the use of images)-->
            <BODY BGCOLOR="White">
            <body>
            <div Style="align:center;">
            <p>
            <img src="IMAGE_URL" alt= "IMAGE_NAME">
            </p>
            </div>
            </br>
            <div style=" height="40" align="left">

            <font size="3" color="#000000" style="text-decoration:none;font-family:Lato light">
            <div class="info" Style="align:left;">

            <p>information here<!--(im sure you know how to write html ;))--></p>

            <br>

            <p>Location:  '.$location.' <!-- $location is the variable you wish to insert as is $date etc --> </p>

            <p>Date:      '.$date.'      </p>

            <p>Time:      '.$startAt.'   </p>

            <p>Duration:  '.$duration.'  </p>

            <p>Company:   '.$company.'   </p>

                '. /* <p>Charge:    '.$charge.'    </p> */'
            <br>

                <p>Reference Number: '.$userId.'</p>

                            </div>

            </br>
            <p>-----------------------------------------------------------------------------------------------------------------</p>
            </br>
            <p>( This is an automated message, please do not reply to this message, if you have any queries please contact [email protected] )</p>
            </font>
            </div>
            </body>
        '."\n\n".
                                                                    $bound_last;

    $sent = mail($to, $subject, $message, $headers); // finally sending the email


}

This should definitely work (as long as you replace INSERT_... etc), other than that I can't see anything wrong with your code immediately, only thing i can really recommend Is checking your applications error logs, it should give you an indication if anything is wrong.

Else check your php ini file to see if sendmail is activated :)

Regards Steve.

--------- edit ---------

so your new code should be along the lines of;

<?php
    $email =$_POST['email'];

    public function sendMail($email, $userId)
{
   $to = $email;
$subject = 'Password Reset';

$bound_text = "----*%$!$%*";
$bound = "--".$bound_text."\r\n";
$bound_last = "--".$bound_text."--\r\n";

$headers = "From: [email protected]\r\n";
$headers .= "MIME-Version: 1.0\r\n" .
        "Content-Type: multipart/mixed; boundary=\"$bound_text\""."\r\n" ;

$message = " you may wish to enable your email program to accept HTML \r\n".
        $bound;

    $message .=
  'Content-Type: text/html; charset=UTF-8'."\r\n".
  'Content-Transfer-Encoding: 7bit'."\r\n\r\n".
  '

        <BODY BGCOLOR="White">
        <body>

        </br>
        <div style=" height="40" align="left">

        <font size="3" color="#000000" style="text-decoration:none;font-family:Lato light">
        <div class="info" Style="align:left;">

        <p>place link here for password reset</p>

         <p>Reference Number: '.$userId.'</p>

                        </div>

        </br>
        <p>-----------------------------------------------------------------------------------------------------------------</p>
        </br>
        <p>( This is an automated message, please do not reply to this message, if you have any queries please contact [email protected] )</p>
        </font>
        </div>
        </body>
    '."\n\n".
                                                                $bound_last;

$sent = mail($to, $subject, $message, $headers); // finally sending the email


}


    function createRandomPassword() {
    $chars = "ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz0123456789";
    $i = 0;
    $pass = '' ;

    while ($i <= 8) {
        $num = mt_rand(0,61);
        $tmp = substr($chars, $num, 1);
        $pass = $pass . $tmp;
        $i++;
    }
    return $pass;
    }

    $pw = createRandomPassword();
    $query = "UPDATE users SET password= SHA1('$pw') WHERE email = '$email' ";
    $result = mysqli_query($link, $query);
if ($result){
$query3 = "SELECT * FROM users where email = '$email'";
$sql = mysqli_query($link, $query3) or die(mysqli_error());  
$rownum = mysqli_num_rows($sql);

if(!$rownum  ) {
   echo "We can not find your email in our records";
    }

    }
   if($result){
   $this->sendMail($email, $userId); /*does it need to be in a class for $this->? or can you call       functions within the php page without?*/
} ?>

------ edit ------

ok the function call should be sendMail($variableOne, $variableTwo)

if you delete the variables at the start of the sendMail function so it should be function sendMail($email){/*code*/} and try that (the email is required to send the mail)

------ edit ------

I have recently remodeled this function to allow for use of Gmail SMTP, If you check out this Page from RamDev (Check the post by Stephen Penn), I explain the steps as well as the function i built, It may help you understand the process of mail through SMTP.

Thanks again,

Steve