PHP 不实现 SMTP 协议 (RFC 5321) 或 IMF (RFC 5322) 或 MIME,例如 Python。取而代之的是——所有 PHP 都是一个简单的围绕 sendmail MTA 的 C 包装器。
但是 - 尽管有所有缺点 - 仍然可以创建 mime 消息(多部分/替代、多部分/混合等)并发送 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);
由于这些限制,大多数人最终会使用第三方库,例如:
- PHPmailer (download)
- Swiftmailer
- 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.';
}
另外:
问:我的主机上需要 smtp 服务器吗?我可以在任何免费托管中这样做吗?
A: 现在任何共享主机都有 SMTP 服务器(sendmail/postfix)。