PHP Mail 学习笔记

简介

PHP Mail 是一个基于 PHP 的邮件发送组件。借助 PHP Mail,您可以在程序中轻松地发送电子邮件。这个组件提供了一个灵活的界面,使您可以设置邮件内容、收件人、附件等。

实例

发送简单邮件

以下代码演示如何使用 PHP Mail 组件发送简单邮件:

Copy Code
$to = 'recipient@example.com'; $subject = 'Test email'; $message = 'Hello world!'; $headers = 'From: sender@example.com' . "\r\n" . 'Reply-To: sender@example.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); mail($to, $subject, $message, $headers);

上述代码中,“to”代表收件人邮箱地址,“to”代表收件人邮箱地址,“subject”代表邮件主题,“message”代表邮件正文,“message”代表邮件正文,“headers”代表邮件头信息,包括发件人、回复地址和邮件客户端信息。

发送带附件的邮件

如果您需要发送带附件的电子邮件,可以使用 PHP Mail 的 MIME 类型实现。以下代码演示如何使用 PHP Mail 发送带附件的邮件:

Copy Code
$to = 'recipient@example.com'; $subject = 'Test email with attachment'; $message = 'Please see attached file.'; $filename = '/path/to/filename.pdf'; $filecontent = file_get_contents($filename); $filetype = mime_content_type($filename); $filename = basename($filename); $boundary = md5(time()); $headers = "From: sender@example.com\r\n" . "Reply-To: sender@example.com\r\n" . "MIME-Version: 1.0\r\n" . "Content-Type: multipart/mixed; boundary=\"{$boundary}\""; $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: {$filetype}; name=\"{$filename}\"\r\n" . "Content-Disposition: attachment; filename=\"{$filename}\"\r\n" . "Content-Transfer-Encoding: base64\r\n\r\n" . chunk_split(base64_encode($filecontent)) . "\r\n--{$boundary}--"; mail($to, $subject, $body, $headers);

上述代码中,“$filename”代表附件文件路径,通过 MIME 类型设置附件类型和编码方式以及邮件头信息。

结语

PHP Mail 是一个非常实用的邮件发送组件,它为我们在 PHP 中发送电子邮件提供了方便和灵活性。