2012-10-09 127 views
0

我有這樣的代碼的形式發送電子郵件在PHP當表單提交

<?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 protected]' . "\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"); 
     } 

    ?> 

我希望它做的是,當有人註冊他們得到一封電子郵件說歡迎。這不起作用我正在嘗試將'to'更改爲他們在表單中提交的電子郵件地址。

有關如何實現此目的的任何想法?

+2

[SSCCE](http://sscce.org)。即您發佈了比所需更多的代碼。 – keyser

+0

PHP郵件功能僅適用於不在本地主機上的Web服務器。你在網絡服務器上測試過你的代碼嗎? –

+0

您可以使用Gmail作爲您的SMTP服務器... –

回答

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 = "[email protected]"; // GMAIL username 
$mail->Password = "password";   // GMAIL password 
$mail->From  = "[email protected]"; 
$mail->FromName = "Admin"; 
$mail->Subject = "Welcome"; 
$mail->WordWrap = 50; // set word wrap 
$mail->AddReplyTo("[email protected]","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,讓他們在你的根

編輯:

在寄存器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>"; 
+0

當我將'到'更改爲我的電子郵件地址時,我可以發送電子郵件,但是當我嘗試將其更改爲以不發送電子郵件的形式提交的變量時'',因此無法發送電子郵件不是我的問題;所以一個不同的smtp服務器不會幫助;任何其他想法;謝謝你的幫助 – Adam

+0

@Adam你還沒有檢索電子郵件ID ...而不是直接給'$ login',你必須給$ _POST ['login'] ..檢查編輯 –

+0

好吧,我會嘗試 – Adam

2

披露:我的背後AlphaMail

我會建議你使用一個事務性的電子郵件服務,如開發商之一:

爲什麼?

  • 您不必多想那麼多關於電子郵件傳遞。
  • 統計。讓我們跟蹤總髮送/點擊/打開/反彈。
  • 通常基於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", "[email protected]")) 
    ->setReceiver(new EmailContact("Joe Doe", "[email protected]")) 
    ->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>