PHP eMailing脚本

时间:2012-10-26 10:38:05

标签: php html email user-accounts

所以我编写了一个php脚本,它会在忘记密码时向用户发送一个临时密码,以便他们可以登录并更改密码。该脚本工作正常,电子邮件将与所有正确的信息一起发送。我想改变的是它是由谁发送的。我想使用谷歌电子邮件应用程序来发送这些电子邮件,而不是我的网络服务器发送的电子邮件。以下是我的脚本发送部分的内容:

$email_to = $_POST["email"];
$email_from = "Admin@domain.com";
$email_subject = "Account Information Recovery";
$email_message = "Here is your temporary password:\n\n";

$email_message .= "Password: ".$password."\n";
$email_message .= "\nPlease log into your account and immediately change your password.";

// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);

但是,当我收到电子邮件时,它来自Admin@webserver。如何使用谷歌的电子邮件应用程序发送这些电子邮件?

2 个答案:

答案 0 :(得分:2)

可能最好使用PHPMailer

$mail = new PHPMailer(); 
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1; //1 for debugging, spits info out  
$mail->SMTPAuth = true;  
$mail->SMTPSecure = 'ssl'; //needed for GMail
$mail->Host = 'smtp.gmail.com';
$mail->Port = 465; 
$mail->Username = 'google_username';  
$mail->Password = 'google_password';           
$mail->SetFrom($email_from, 'Your Website Name');
$mail->Subject = $email_subject;
$mail->Body = $email_message;
$mail->AddAddress($email_to);
$mail->Send();

注意:此示例直接使用SMTP发送电子邮件,这将解决问题,但如果主机已禁用fsockopen,则无法使用。

答案 1 :(得分:1)

我建议Swiftmailer。它有一个非常好的,记录良好的API,并支持所有不同类型的传输。

来自文档:

require_once 'lib/swift_required.php';

// Create the Transport
$transport = Swift_SmtpTransport::newInstance('smtp.example.org', 25)
  ->setUsername('your username')
  ->setPassword('your password')
  ;

/*
You could alternatively use a different transport such as Sendmail or Mail:

// Sendmail
$transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs');

// Mail
$transport = Swift_MailTransport::newInstance();
*/

// Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);

// Create a message
$message = Swift_Message::newInstance('Wonderful Subject')
  ->setFrom(array('john@doe.com' => 'John Doe'))
  ->setTo(array('receiver@domain.org', 'other@domain.org' => 'A name'))
  ->setBody('Here is the message itself')
  ;

// Send the message
$result = $mailer->send($message);