ホームページ  >  記事  >  バックエンド開発  >  PHPの組み込み関数を使用してメールを送受信するにはどうすればよいですか?

PHPの組み込み関数を使用してメールを送受信するにはどうすればよいですか?

PHPz
PHPzオリジナル
2024-04-22 14:24:02467ブラウズ

PHP 組み込み関数は、電子メールを送受信する機能を提供します。電子メールを送信するには、受信者、電子メールの件名、電子メールの内容、ヘッダー情報を指定し、mail() 関数を使用して送信する必要があります。電子メールを受信するには、メールボックス接続を開いてメッセージを取得し、pop3_get_all() 関数を使用してすべてのメッセージを取得する必要があります。より複雑なアプリケーション シナリオの場合は、マルチパート/混合コンテンツ タイプを指定してファイルを添付することで、添付ファイル付きの電子メールを送信することもできます。

如何使用 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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。