>  기사  >  백엔드 개발  >  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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.