Sending an automated email

38,580

Solution 1

Simplest way to do that:

  1. Make HTML form on your page:

    <form method="POST" action="email-script.php">
        <label for="email">Email:</label>
        <input type="text" name="email" id="email" />
        <input type="submit" value="Ok" />
    </form>
    
  2. Write PHP code in your email-script.php file:

    <?php
        $email=$_POST['email'];
        $subject = 'Your subject for email';
        $message = 'Body of your message';
    
        mail($email, $subject, $message);
    ?>
    

When you master this simple method, you can use more advanced method with AJAX (so you don't need to reload page) or SMTP (which gives you more control over sending mails to users).

Solution 2

You can send an email through PHP, but most of the answers on SO saying "use the mail() function" are outdated I presume and, in any case, do not work.

I would advise you to use JavaScript or simply an HTML form collecting a user ID or user email. Then pass that on as a parameter to your post function that calls the PHP you want to run.

In the PHP file, you read the email (for example, via $_POST['email']). Then you run a SQL query to retrieve the password WHERE the email is equal to the one you just read.

Finally, since you now have the password stored in a variable, you continue in your PHP file and use PHPMailer's function, as shown in examples like the following: https://github.com/PHPMailer/PHPMailer/blob/master/examples/mail.phps. Alternatively, you could use a similar library to achieve the same functionality.

Then you put the password in your email text and send it to the user.

However, a note of caution: it would be very unwise in terms of security to send passwords in plain text format (not encrypted) to a user's email address. I would advise you to send them an email with a password reset link instead, which would direct them to a form where they could select a new password and confirm it. That would require a different PHP file, where you would execute an UPDATE query to change the password that is stored in the database.

I assume you have already solved your problem, since this is an old question, but maybe this will help someone else who stumbles upon it.

Share:
38,580
TheQuantumBros
Author by

TheQuantumBros

Updated on March 04, 2020

Comments

  • TheQuantumBros
    TheQuantumBros about 4 years

    I would like to have an automated email sent to a person's email when they press a button. I'm having a few problems, one I am not sure what the JavaScript for this would be. Two, I don't know how to mix both PHP and JavaScript, since I need to use PHP to get their email address and password from an SQL Table, and as far as I know, I need JavaScript to send the email. Finally, I am not sure how to add the password from the PHP into the email. Help on any of these would be greatly appreciated. Thanks.