如何通过SMTP发送电子邮件?

时间:2014-06-24 16:46:54

标签: php email smtp

我需要在注册帐户时向新用户和我自己发送电子邮件。我需要知道如何通过我的管理员电子邮件发送,而不是GoDaddy服务器用来发送它的奇怪电子邮件地址。

这是我的PHP代码:

<?php
  require_once('recaptchalib.php');
  $privatekey = "privatekey";
  $resp = recaptcha_check_answer ($privatekey,
                                $_SERVER["REMOTE_ADDR"],
                                $_POST["recaptcha_challenge_field"],
                                $_POST["recaptcha_response_field"]);

  if (!$resp->is_valid) {
    die ("reCAPTCHA was wrong, try again!");
  } else {
mysql_connect("host", "username", "password");
mysql_select_db("database");

$hash = sha1(rand (0,1000) );
$name = $_POST['name'];
$bmonth = $_POST['month'];
$bday = $_POST['day'];
$byear = $_POST['year'];
$sq = $_POST['security_q'];
$sq_ans = sha1($_POST['security_q_ans']);
$email = $_POST['email'];
$pass = sha1($_POST['pass']);

$insert_query = "INSERT INTO users (account_act_hash, name, bmonth, bday, byear, securityq, securityq_ans, email, password) VALUES ('$hash','$name','$bmonth','$bday','$byear','$sq','$sq_ans','$email','$pass')";
$insertion_result = mysql_query($insert_query);
if($insertion_result) {

$to = "my admin email";
$subject = "New account created";
$name = $_POST['name'];
$bmonth = $_POST['month'];
$bday = $_POST['day'];
$byear = $_POST['year'];
$email = $_POST['email'];
$ip = $_SERVER['REMOTE_ADDR'];

$message = 'EMAIL

Here is the account info.

Name: $name
Birthday: $bmonth-$bday-$byear
Email: $email

Registration IP Address: $ip

'

$header = "A new account has been created.";
}

if($_POST){
    mail($to, $subject, $message, $header);
}
  }
  ?>
<?php
$to2 = $_POST['email'];
$subject2 = "Activate Your Account";
$email2 = $_POST['email'];

$message2 = '
Thanks for registering an account!
Your account has been created and can be used when you activate your account by clicking the below link!

------------------------------------------------------------------------
Email: '.$email2.'
------------------------------------------------------------------------

Please click this link to activate your account:
https://www.mysite.com/activation.php?email='.$email2.'&account_act_hash='.$hash.'
';
if($_POST) {
mail($to2, $subject2, $message2);
}
?>

1 个答案:

答案 0 :(得分:1)

直接来自标题中需要指定的mail doc page

// Additional headers
$headers .= 'From: Birthday Reminder <birthday@example.com>' . "\r\n";

您收到的是一个奇怪的电子邮件地址_,因为您尚未指定电子邮件的来源。

您还有许多其他问题:

HEREDOC

我假设这是你想要做的事情

$message = <<<EMAIL

Here is the account info.

Name: $name
Birthday: $bmonth-$bday-$byear
Email: $email

Registration IP Address: $ip

EMAIL;

的MySQL

mysql_*函数为deprecated,请阅读阅读框。

这也会导致不信任用户输入prepared statements将成为您的朋友。

其它

使用双引号时,请使用带有变量的花括号:

$foo = 'test';
echo "This a {$foo}!"; // This is a test!

在这种情况下die(),在用户体验方面结束脚本是一种非常苛刻的方式。