如何使用 PHP 內建函數傳送和接收電子郵件?

PHPz
發布: 2024-04-22 14:24:02
原創
487 人瀏覽過

PHP 內建函數提供了傳送和接收電子郵件的功能。發送電子郵件需指定收件者、郵件主旨、郵件內容及首部訊息,使用 mail() 函數傳送。接收電子郵件需開啟郵箱連接,取得訊息,並使用 pop3_get_all() 函數取得全部訊息。在更複雜的應用程式場景中,也可以傳送附有附件的電子郵件,透過指定 multipart/mixed 內容類型並附加檔案來實現。

如何使用 PHP 内置函数发送和接收电子邮件?

如何使用 PHP 內建函數傳送和接收電子郵件

#PHP 提供了一系列內建函數,用於傳送和接收電子郵件到遠端伺服器。本文將指導您如何使用這些函數來建立一個基本的電子郵件處理程序。

發送電子郵件

<?php
// 设置邮件参数
$to = 'recipient@example.com';
$subject = 'Test Email';
$message = 'Hello there! This is a test email.';
$headers = "From: sender@example.com\r\n";
$headers .= "Reply-To: sender@example.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/plain; charset=utf-8\r\n";

// 发送邮件
if (mail($to, $subject, $message, $headers)) {
  echo "Email sent successfully.";
} else {
  echo "Email could not be sent.";
}
?>
登入後複製

接收電子郵件

<?php
// 检查邮件
$mailbox = pop3_open('{pop.example.com:110}INBOX', 'username', 'password');

// 读取消息
$messages = pop3_get_all($mailbox);

// 输出消息
foreach ($messages as $message) {
  echo 'From: ' . $message['from'] . PHP_EOL;
  echo 'Subject: ' . $message['subject'] . PHP_EOL;
  echo 'Body: ' . $message['body'] . PHP_EOL;
  echo '-----------------------' . PHP_EOL;
}

// 关闭邮箱连接
pop3_close($mailbox);
?>
登入後複製

實戰案例

<?php
// 发送带有附件的电子邮件
$to = 'recipient@example.com';
$subject = 'Email with Attachment';
$message = 'Please find the attached document for your review.';
$attachment = 'document.pdf';
$headers = "From: sender@example.com\r\n";
$headers .= "Reply-To: sender@example.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"==BOUNDARY==\"\r\n";
$headers .= "Content-Transfer-Encoding: 7bit\r\n";

// 准备邮件正文
$body = "This is a MIME encoded message.\r\n\r\n";
$body .= "--==BOUNDARY==\r\n";
$body .= "Content-Type: text/plain; charset=\"UTF-8\"\r\n";
$body .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$body .= $message . "\r\n";

// 附加文件
$body .= "--==BOUNDARY==\r\n";
$body .= "Content-Type: application/octet-stream; name=\"" . basename($attachment) . "\"\r\n";
$body .= "Content-Disposition: attachment\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n\r\n";
$body .= chunk_split(base64_encode(file_get_contents($attachment))) . "\r\n";

// 发送电子邮件
if (mail($to, $subject, $body, $headers)) {
  echo "Email with attachment sent successfully.";
} else {
  echo "Email could not be sent.";
}
?>
登入後複製

以上是如何使用 PHP 內建函數傳送和接收電子郵件?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!