PHP mail() 함수

정의와 사용법

mail() 함수는 스크립트에서 직접 이메일을 보낼 수 있게 합니다。

이메일의 전달이 성공적으로 접수되면 true를 반환하며, 그렇지 않으면 false를 반환합니다。

문법

mail(to,subject,message,headers,parameters)
매개변수 설명
to 필수. 이메일의 수신자를 지정합니다.
subject 필수. 이메일의 제목을 지정합니다. 이 매개변수는 줄 바꿈 문자를 포함할 수 없습니다.
message 필수. 보내야 할 메시지를 지정합니다.
headers 필수. 추가 헤더를 지정합니다. 예를 들어 From, Cc 및 Bcc.
parameters 필수. sendmail 프로그램의 추가 매개변수를 지정합니다.

설명

내에서 message 매개변수로 지정된 메시지에서는 행 사이에LF(\n)로 구분되어야 하며, 한 행은 70자를 초과할 수 없습니다。

(Windows에서)PHP가 직접 SMTP 서버에 연결할 때, 한 행의 시작에句号이 발견되면 지워집니다. 이 문제를 피하기 위해 단일句号을 두 개의句号으로 변경하세요。

<?php
$text = str_replace("\n.", "\n..", $text);
?>

팁과 주석

주석:이메일이 접수되었음을 의미하지만 이메일이 목표지에 도착했음을 의미하지 않습니다.

예제

예제 1

간단한 이메일을 보내기:

<?php
$txt = "First line of text\nSecond line of text";
// 한 행이 70자를 초과하면 wordwrap()를 사용하세요。
$txt = wordwrap($txt,70);
// 이메일을 보내기
mail("somebody@example.com","My subject",$txt);
?>

예제 2

이메일을 보내기 위해 추가 헤더를 포함한 이메일을 보내세요:

<?php
$to = "somebody@example.com";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: webmaster@example.com" . "\r\n" .
"CC: somebodyelse@example.com";
mail($to,$subject,$txt,$headers);
?>

예제 3

HTML 이메일을 보내는 예제:

<?php
$to = "somebody@example.com, somebodyelse@example.com";
$subject = "HTML 이메일";
$message = "
<html>
<head>
<title>HTML 이메일</title>
</head>
<body>
<p>This email contains HTML Tags!</p>
<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>
<tr>
<td>Bill</td>
<td>Gates</td>
</tr>
</table>
</body>
</html>
";
// HTML 이메일을 보내면 항상 content-type을 설정하십시오
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
// 추가 헤더
$headers .= 'From: <webmaster@example.com>' . "\r\n";
$headers .= 'Cc: myboss@example.com' . "\r\n";
mail($to,$subject,$message,$headers);
?>