PHP没有实现SMTP协议(RFC 5321)或IMF(RFC 5322),也没有像Python一样实现MIME。相反,PHP只有一个简单的C封装器,用于sendmail MTA。
然而,尽管存在所有这些缺点,人们仍然可以使用默认的PHP mail()函数创建mime消息(multipart/alternative、multipart/mixed等),发送HTML和文本消息,并附加文件。问题在于 - 这不是直观的。您将使用“headers”邮件()参数手工制作整个消息,同时将“message”参数设置为''。此外,通过PHP的mail()循环发送电子邮件将是性能浪费,因为mail()为每个新电子邮件打开新的smtp连接。
$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 (下载)
- Swiftmailer
- Zend_Mail
使用这些库可以轻松构建文本或HTML消息。添加文件也变得很容易。
require("class.phpmailer.php");
$mail = new PHPMailer();
$mail->From = "from@example.com";
$mail->FromName = "Your Name";
$mail->AddAddress("myfriend@example.net");
$mail->Subject = "An HTML Message";
$mail->IsHTML(true);
$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())
{
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
}
else
{
echo 'Message has been sent.';
}
此外:
问:我需要在我的主机上安装SMTP服务器吗?我可以在任何免费的托管服务中使用它吗?
答:现在任何共享托管服务都有SMTP服务器(sendmail/postfix)。