邮件()与PHP

nik*_*kky 4 php

我想编写一个脚本,使用php自动向我的客户端发送电子邮件

如何自动发送,例如,如果他们输入电子邮件.并单击"提交"

我想自动发送这封电子邮件

第二,我的主机上需要smtp服务器吗?我可以在任何免费托管中吗?

谢谢你们,我很抱歉我的语言

Nikky

Pas*_*TIN 6

我可能不会mail直接使用这个功能:太多你需要关心的事情......

相反,我建议使用一些与邮件相关的库,它将为您处理很多事情.

其中一个(现在似乎取得了一些成功 - 例如它被集成在Symfony框架中)Swift Mailer.

当然,对于一个简单的邮件来说可能有点过分......但是花一些时间学习如何使用这样的库总是值得的;-)


小智 6

例如,PHP没有实现SMTP协议(RFC 5321)或IMF(RFC 5322),或者像Python这样的MIME.相反 - 所有PHP都是sendmail MTA的简单C包装器.

然而 - 尽管有它的缺点 - 人们仍然可以创建mime消息(multipart/alternative,multipart/mixed等)并发送html和文本消息,并使用默认的PHP的mail()函数附加文件.问题是 - 这不是直截了当的.您最终将使用"headers"mail()参数手工制作整个消息,同时将"message"参数设置为''.此外 - 通过PHP的mail()循环发送电子邮件将是一种性能浪费,因为mail()为每个新电子邮件打开了新的smtp连接.

/**sending email via PHP's Mail() example:**/
$to      = 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com' . "\r\n" .
    'Reply-To: webmaster@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);
Run Code Online (Sandbox Code Playgroud)

由于这些限制,大多数人最终使用第三方库,如:

  1. PHPmailer(下载)
  2. Swiftmailer
  3. 使用Zend_Mail

使用这些库可以轻松构建文本或html消息.添加文件也很容易.

/*Sending email using PHPmailer example:*/
require("class.phpmailer.php");
$mail = new PHPMailer();

$mail->From = "from@example.com";
$mail->FromName = "Your Name";
$mail->AddAddress("myfriend@example.net"); // This is the adress to witch the email has to be send. 
$mail->Subject = "An HTML Message";
$mail->IsHTML(true); // This tell's the PhPMailer that the messages uses HTML.
$mail->Body = "Hello, <b>my friend</b>! \n\n This message uses HTML !";
$mail->AltBody = "Hello, my friend! \n\n This message uses HTML, but your email client did not support it !";

if(!$mail->Send()) // Now we send the email and check if it was send or not.
{
   echo 'Message was not sent.';
   echo 'Mailer error: ' . $mail->ErrorInfo;
}
else
{
   echo 'Message has been sent.';
}
Run Code Online (Sandbox Code Playgroud)

另外:问:我的主机上是否需要smtp服务器?我可以在任何免费托管中吗?答:现在任何共享主机都有SMTP服务器(sendmail/postfix).