提交表单时使用PHP发送电子邮件

时间:2012-10-09 09:46:12

标签: php html email

我有一个表单的代码

 <?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>

然后该表单运行此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");
        }

    ?>

我想要它做的是当有人注册时他们收到一封电子邮件说欢迎。这不起作用我试图改变&#39;到&#39;到他们在表单中提交的电子邮件地址。

关于如何实现这一目标的任何想法?

2 个答案:

答案 0 :(得分:2)

披露:我是AlphaMail背后的开发者之一

我建议您使用交易电子邮件服务,例如:

<强>为什么吗

  • 您不必过多考虑电子邮件投放。
  • 统计。让我们跟踪Total Sent / Clicks / Opens / Bounces。
  • 通常是基于Web服务而不是SMTP。即更容易处理。
  • 清洁代码(至少如果您使用AlphaMail将数据与演示文稿分开)。
  • 可扩展且面向未来。

如果您选择使用AlphaMail,则可以使用AlphaMail PHP-client

示例:

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
);

AlphaMail的另一个优势是您可以直接在AlphaMail Dashboard中修改模板,并且可以使用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>

答案 1 :(得分:0)

使用gmail作为邮件服务器。

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");
}

下载class.phpmailer.phpclass.smtp.php并将其保存在您的根

修改

在register-exec.php中,

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

您可以使用这些变量..赞

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