PHP发送电子邮件

时间:2020-01-09 10:43:00  来源:igfitidea点击:

问题描述:如何在Linux/UNIX操作系统下使用PHP和Apache网络服务器发送电子邮件?
如何从PHP脚本发送电子邮件?

解决方法:PHP下的mail()函数允许您发送邮件。
为了使Mail功能可用,PHP在编译期间必须有权访问系统上的sendmail二进制文件。
通常,大多数Web服务器都是使用sendmail二进制文件安装的。

示例PHP发送电子邮件代码

<?php
// Send to?
$to = "[email protected]";
 
// The Subject
$subject = "Email Test";
 
// The message
$message = "This is a test.\n
How much is Linux worth today?\n
End of email message!";
 
// In case any of our lines are larger than 70 characters, we should use wordwrap()
$message = wordwrap($message, 70);
 
// Send email
// Returns TRUE if the mail was successfully accepted for delivery, FALSE otherwise. 
// Use if command to display email message status
if ( mail($to, $subject, $message) )
{
     echo("Your email message successfully sent.");
} 
else 
{
     echo("Sorry, message delivery failed. Contact webmaster for more info.");
}
?>

添加电子邮件标题,例如从电子邮件ID

您可以将第四个参数添加到mail()。
通常用于添加额外的标头(From,Cc和Bcc)。
多个额外的标头应以CRLF(\ r \ n)分隔:

<?php
$to = '[email protected]';
$subject = 'Test';
$message = 'This is a test.';
// set headers as per your requirements. 
$headers = 'From: [email protected]' . "\r\n" .
    'Reply-To: [email protected]' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();
 
if ( mail($to, $subject, $message, $headers) ) {
	echo 'Message sent!';
}
else
{
	echo 'Message failed, contact webmaster for more info!';
}
?>