PHP mail()函数实战指南:打造完美邮件发送教程
在PHP中,使用内置的mail()
函数可以发送邮件。这个函数相对简单,但功能有限。以下将详细介绍如何使用mail()
函数发送邮件,包括其参数、使用示例以及一些常见的配置和问题。
函数原型
bool mail(string $to, string $subject, string $message, string $additional_headers = "", string $additional_parameters = "");
参数说明
$to
: 接收邮件的地址,可以是单个地址或多个地址,使用逗号分隔。$subject
: 邮件的主题。$message
: 邮件正文内容。$additional_headers
: 额外的邮件头信息,如From
,Cc
,Bcc
等。$additional_parameters
: 额外的参数,通常用于传递SMTP服务器的信息。
使用示例
以下是一个使用mail()
函数发送简单文本邮件的示例:
$to = 'recipient@example.com';
$subject = 'Test Email Subject';
$message = 'This is a test email message.';
$headers = 'From: sender@example.com' . "\r\n" .
'Reply-To: sender@example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
if(mail($to, $subject, $message, $headers)) {
echo 'Email sent successfully!';
} else {
echo 'Failed to send email!';
}
发送HTML邮件
如果要发送HTML内容的邮件,需要在邮件头中添加Content-Type
字段:
$to = 'recipient@example.com';
$subject = 'Test HTML Email Subject';
$message = '<h1>This is a test HTML email message.</h1><p>Enjoy this HTML content!</p>';
$headers = 'From: sender@example.com' . "\r\n" .
'Reply-To: sender@example.com' . "\r\n" .
'Content-Type: text/html; charset=UTF-8' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
if(mail($to, $subject, $message, $headers)) {
echo 'HTML Email sent successfully!';
} else {
echo 'Failed to send HTML email!';
}
发送带附件的邮件
发送带附件的邮件需要使用多部分邮件格式,以下是一个发送带附件的邮件的示例:
$to = 'recipient@example.com';
$subject = 'Test Email with Attachment';
$message = 'This email has an attachment.';
$headers = 'From: sender@example.com' . "\r\n" .
'MIME-Version: 1.0' . "\r\n" .
'Content-Type: multipart/mixed; boundary="Boundary_123"' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$boundary = 'Boundary_123';
$body = "--$boundary\r\n" .
"Content-Type: text/plain; charset=UTF-8\r\n" .
"Content-Transfer-Encoding: 7bit\r\n\r\n" .
$message . "\r\n\r\n" .
"--$boundary\r\n" .
"Content-Type: application/octet-stream; name=\"file.txt\"\r\n" .
"Content-Transfer-Encoding: base64\r\n" .
"Content-Disposition: attachment; filename=\"file.txt\"\r\n\r\n" .
chunk_split(base64_encode(file_get_contents('file.txt'))) . "\r\n" .
"--$boundary--";
if(mail($to, $subject, $body, $headers)) {
echo 'Email with attachment sent successfully!';
} else {
echo 'Failed to send email with attachment!';
}