简体   繁体   中英

Send Email in PHP When Form is Submitted

I have this code for a form

 <?php
    session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Register</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<center><table width="1074" height="768" border="0" cellspacing="5" cellpadding="10" div style="width: 1065; height: *px; background:#FFFFFF;">
<tr>
<td bgcolor="#88bbdd">
<body>
<?php
    if( isset($_SESSION['ERRMSG_ARR']) && is_array($_SESSION['ERRMSG_ARR']) && count($_SESSION['ERRMSG_ARR']) >0 ) {
        echo '<ul class="err">';
        foreach($_SESSION['ERRMSG_ARR'] as $msg) {
            echo '<li>',$msg,'</li>'; 
        }
        echo '</ul>';
        unset($_SESSION['ERRMSG_ARR']);
    }
?>
<div align="center">
<table>
<form id="registerForm" name="registerForm" method="post" action="register-exec.php">
<tr>
<td><div align="left">*First Name           <td><input name="fname" type="text" class="textfield" id="fname" /></div>
<tr>
<td><div align="left">*Last Name        <td><input name="lname" type="text" class="textfield" id="lname" /></div>
<tr>
<td><div align="left">*Email Address    <td><input name="login" type="text" class="textfield" id="login" /></div>
<tr>
<td><div align="left">*Password     <td><input name="password" type="password" class="textfield" id="password" /></div>
<tr>
<td><div align="left">*Confirm Password <td><input name="cpassword" type="password" class="textfield" id="cpassword" /></div> 
</tr>
</table>
<br><br>
<input type="submit" name="Submit" value="Register" />  
</form>
<br><br>* Indicates a Required Field
</div>
</td>
</tr>
</table>
</body>
</html>

Then that form runs this PHP

<?php
// multiple recipients
$to  = $login;

// subject
$subject = 'Subject';

// message
$message = '
<html>
<head>
  <title>Email</title>
</head>
<body>
  <p>Content</p> 
</body>
</html>
';

// To send HTML mail, the Content-type header must be set
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

// Additional headers
$headers .= 'To: $fname $lname. "\r\n";
$headers .= 'From: email@mydomain.com' . "\r\n";

// Mail it
mail($to, $subject, $message, $headers);
?>

    <?php
        //Start session
        session_start();

        //Include database connection details
        require_once('config.php');

        //Array to store validation errors
        $errmsg_arr = array();

        //Validation error flag
        $errflag = false;

        //Connect to mysql server
        $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
        if(!$link) {
            die('Failed to connect to server: ' . mysql_error());
        }

        //Select database
        $db = mysql_select_db(DB_DATABASE);
        if(!$db) {
            die("Unable to select database");
        }

        //Function to sanitize values received from the form. Prevents SQL injection
        function clean($str) {
            $str = @trim($str);
            if(get_magic_quotes_gpc()) {
                $str = stripslashes($str);
            }
            return mysql_real_escape_string($str);
        }

        //Sanitize the POST values
        $fname = clean($_POST['fname']);
        $lname = clean($_POST['lname']);
        $login = clean($_POST['login']);
        $password = clean($_POST['password']);
        $cpassword = clean($_POST['cpassword']);

        //Input Validations
        if($fname == '') {
            $errmsg_arr[] = 'First name missing';
            $errflag = true;
        }
        if($lname == '') {
            $errmsg_arr[] = 'Last name missing';
            $errflag = true;
        }
        if($login == '') {
            $errmsg_arr[] = 'Email Address missing';
            $errflag = true;
        }
        if($password == '') {
            $errmsg_arr[] = 'Password missing';
            $errflag = true;
        }
        if($cpassword == '') {
            $errmsg_arr[] = 'Confirm password missing';
            $errflag = true;
        }
        if( strcmp($password, $cpassword) != 0 ) {
            $errmsg_arr[] = 'Passwords do not match';
            $errflag = true;
        }

        //Check for duplicate login ID
        if($login != '') {
            $qry = "SELECT * FROM members WHERE login='$login'";
            $result = mysql_query($qry);
            if($result) {
                if(mysql_num_rows($result) > 0) {
                    $errmsg_arr[] = 'Login ID already in use';
                    $errflag = true;
                }
                @mysql_free_result($result);
            }
            else {
                die("Query failed");
            }
        }

        //If there are input validations, redirect back to the registration form
        if($errflag) {
            $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
            session_write_close();
            header("location: register-form.php");
            exit();
        }

        //Create INSERT query
        $qry = "INSERT INTO members(firstname, lastname, login, passwd) VALUES('$fname','$lname','$login','".md5($_POST['password'])."')";
        $result = @mysql_query($qry);

        //Check whether the query was successful or not
        if($result) {
            header("location: register-success.php");
            exit();
        }else {
            die("Query failed");
        }

    ?>

What I want it to do is when someone registers they get an email saying welcome. This does not work I am trying to change the 'to' to the email address they submitted in the form.

Any ideas on how I can Achieve this?

Disclosure: I'm one of the developers behind AlphaMail

I would recommend that you use a Transactional Email Service such as:

Why?

  • You don't have to think that much about email delivery.
  • Statistics. Let's you track Total Sent/Clicks/Opens/Bounces.
  • Often web service-based instead of SMTP. Ie easier to handle.
  • Cleaner code (at least if you use AlphaMail that separates data from presentation).
  • Scalable and future proof.

If you choose to go with AlphaMail you could use the AlphaMail PHP-client .

Example:

include_once("comfirm.alphamail.client/emailservice.class.php");

$email_service = AlphaMailEmailService::create()
    ->setServiceUrl("http://api.amail.io/v1")
    ->setApiToken("YOUR-ACCOUNT-API-TOKEN-HERE");

$person = new stdClass();
$person->userId = "1234";
$person->firstName = "John";
$person->lastName = "Doe";
$person->dateOfBirth = 1975;

$response = $email_service->queue(EmailMessagePayload::create()
    ->setProjectId(12345) // Your AlphaMail project (determines template, options, etc)
    ->setSender(new EmailContact("Sender Company Name", "from@example.com"))
    ->setReceiver(new EmailContact("Joe Doe", "to@example.org"))
    ->setBodyObject($person) // Any serializable object
);

Another advantage with AlphaMail is that you can edit your templates directly in the AlphaMail Dashboard , and you can format your emails using the Comlang template language .

<html>
    <body>
        <b>Name:</b> <# payload.firstName " " payload.lastName #><br>
        <b>Date of Birth:</b> <# payload.dateOfBirth #><br>

        <# if (payload.userId != null) { #>
            <a href="/sign-up">Sign Up Free!</a>
        <# } else { #>
            <a href="/login?id=<# payload.userId #>">Sign In</a>
        <# } #>
    </body>
</html>

Use gmail as your mail server.

require_once('class.phpmailer.php');
include_once('class.smtp.php');
$mail = new PHPMailer(); // defaults to using php "mail()"
$body = "<html></html>"; //html stuff
$mail->IsSMTP();
$mail->SMTPAuth   = true;                  // enable SMTP authentication
$mail->SMTPSecure = "ssl";                 // sets the prefix to the server
$mail->Host       = "smtp.gmail.com";      // sets GMAIL as the SMTP server
$mail->Port       = 465;                   // set the SMTP port
$mail->Username   = "id@gmail.com";  // GMAIL username
$mail->Password   = "password";            // GMAIL password
$mail->From       = "id@gmail.com";
$mail->FromName   = "Admin";
$mail->Subject    = "Welcome";
$mail->WordWrap   = 50; // set word wrap
$mail->AddReplyTo("id@gmail.com","Admin");
$mail->AddAddress($email_id); //receiver's id
$mail->IsHTML(true); // send as HTML
$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; 
$mail->MsgHTML($body);

if(!$mail->Send()){
  $msg = "Mailer Error: ".$mail->ErrorInfo;
  header("Location: http://{$_SERVER['HTTP_HOST']}/site/index.php?msg=$msg");
}else{
    $msg="Message sent successfully!";
    header("Location: http://{$_SERVER['HTTP_HOST']}/site/index.php?msg=$msg");
}

Download class.phpmailer.php and class.smtp.php and keep them in your root

EDIT:

In register-exec.php,

$to  = $_POST['login'];
$name = $_POST['fname'];
$password = $_POST['password']; // you've given the name as 'password' in your form

You can use these variables..like

$body = "<div>Hi '.$name.'!<br>Your id:'.$to.',<br>Your Password:'.$password.'</div>";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM